Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 - Removing duplicates from array of objects

Assuming an array of objects as follows:

const listOfTags = [     {id: 1, label: "Hello", color: "red", sorting: 0},     {id: 2, label: "World", color: "green", sorting: 1},     {id: 3, label: "Hello", color: "blue", sorting: 4},     {id: 4, label: "Sunshine", color: "yellow", sorting: 5},     {id: 5, label: "Hello", color: "red", sorting: 6}, ] 

A duplicate entry would be if label and color are the same. In this case Objects with id = 1 and id = 5 are duplicates.

How can I filter this array and remove duplicates?

I know solutions where you can filter against one key with something like:

const unique = [... new Set(listOfTags.map(tag => tag.label)] 

But what about multiple keys?

As per request in comment, here the desired result:

[     {id: 1, label: "Hello", color: "red", sorting: 0},     {id: 2, label: "World", color: "green", sorting: 1},     {id: 3, label: "Hello", color: "blue", sorting: 4},     {id: 4, label: "Sunshine", color: "yellow", sorting: 5}, ] 
like image 588
Andy Avatar asked Nov 29 '18 15:11

Andy


People also ask

How do you remove duplicates from array of objects?

Array. filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ( {id} destructs the object into only its id). To only filter out actual duplicates, it is using Array.

How do you remove duplicates from an array of arrays?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

How do you get all unique values remove duplicates in a JavaScript array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.


2 Answers

You could use a Set in a closure for filtering.

const      listOfTags = [{ id: 1, label: "Hello", color: "red", sorting: 0 }, { id: 2, label: "World", color: "green", sorting: 1 }, { id: 3, label: "Hello", color: "blue", sorting: 4 }, { id: 4, label: "Sunshine", color: "yellow", sorting: 5 }, { id: 5, label: "Hello", color: "red", sorting: 6 }],      keys = ['label', 'color'],      filtered = listOfTags.filter(          (s => o =>               (k => !s.has(k) && s.add(k))              (keys.map(k => o[k]).join('|'))          )          (new Set)      );    console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 64
Nina Scholz Avatar answered Oct 09 '22 16:10

Nina Scholz


Late one, but I don't know why nobody suggests something much simpler:

listOfTags.filter((tag, index, array) => array.findIndex(t => t.color == tag.color && t.label == tag.label) == index); 
like image 34
Sebastien C. Avatar answered Oct 09 '22 15:10

Sebastien C.