Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of duplicate objects in an array of objects

Tags:

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' } ]; 
like image 409
josh_boaz Avatar asked Nov 08 '18 16:11

josh_boaz


People also ask

How do you find duplicate values in an array of objects in Java?

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.

How do you find duplicate values in an array of objects using Lodash?

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.


2 Answers

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]));
like image 88
ggorlen Avatar answered Oct 06 '22 01:10

ggorlen


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/

like image 32
HMagdy Avatar answered Oct 05 '22 23:10

HMagdy