How to remove duplicates in an ES6 array object based on property values?
By using the Set data structure and the Array.from() method, it is convenient to eliminate duplicates from ES6 arrays based on property values.
Assume there is an ES6 array object with elements that are objects, each containing a unique property that can be used for deduplication. The following steps can be followed:
- Create a new array using the Array.map() method that only contains the unique property values that need to be deduplicated.
- Use the Set data structure to remove duplicates, as Sets automatically eliminate duplicate values.
- You can convert a Set into a new array using the Array.from() method.
Here is an example code:
const arr = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Alice' },
{ id: 4, name: 'David' },
{ id: 5, name: 'Bob' }
];
const uniqueArr = Array.from(new Set(arr.map(item => item.name)));
console.log(uniqueArr);
Running the above code will output: [‘Alice’, ‘Bob’, ‘David’]. This new array contains only unique property values.