I am trying to get duplicate objects within an array of objects. Let's say the object is like below.
values = [ { id: 10, name: 'someName1' }, { id: 10, name: 'someName2' }, { id: 11, name: 'someName3' }, { id: 12, name: 'someName4' } ];
Duplicate objects should return like below:
duplicate = [ { id: 10, name: 'someName1' }, { id: 10, name: 'someName2' } ];
One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.
To get duplicate values from an array with Lodash, we can use the countBy method to count the values. Then we call the JavaScript array's reduce method to get all the items that has count more than 1 and put them in an array.
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]));
Let's say you have:
arr = [ { id:10, name: 'someName1' }, { id:10, name: 'someName2' }, { id:11, name: 'someName3' }, { id:12, name: 'someName4' } ]
So, to get unique items:
unique = arr .map(e => e['id']) .map((e, i, final) => final.indexOf(e) === i && i) .filter(obj=> arr[obj]) .map(e => arr[e]);
Then, result will be
unique = [ { id:10, name: 'someName1' }, { id:11, name: 'someName3' }, { id:12, name: 'someName4' } ]
And, to get duplicate ids:
duplicateIds = arr .map(e => e['id']) .map((e, i, final) => final.indexOf(e) !== i && i) .filter(obj=> arr[obj]) .map(e => arr[e]["id"])
List of IDs will be
duplicateIds = [10]
Thus, to get duplicates objects:
duplicate = arr.filter(obj=> dublicateIds.includes(obj.id));
Now you have it:
duplicate = [ { id:10, name: 'someName1' }, { id:10, name: 'someName2' } ]
Thanks https://reactgo.com/removeduplicateobjects/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With