Get list of duplicate objects in an array of objects Get list of duplicate objects in an array of objects typescript typescript

Get list of duplicate objects in an array of objects


You can use Array#reduce to make a counter lookup table based on the id key, then use Array#filter to remove any items that appeared only once in the lookup table. Time complexity is O(n).

const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];const lookup = values.reduce((a, e) => {  a[e.id] = ++a[e.id] || 0;  return a;}, {});console.log(values.filter(e => lookup[e.id]));