How would you remove the duplicate elements from this array?
const list = [
{ name: 'John' },
{ name: 'Sara' },
{ name: 'Sara' },
{ name: 'Lynn' },
{ name: 'Jake' }
];
How would you remove the duplicate elements from this array?
const list = [
{ name: 'John' },
{ name: 'Sara' },
{ name: 'Sara' },
{ name: 'Lynn' },
{ name: 'Jake' }
];
There are a few ways to do this. Your first intuition might be to do something like this.
const uniqueList = Array.from(new Set(list))
It’s the right idea since creating a Set will ensure our collection only contains unique values and Array.from allows us to create a new, shallow-copied array. Unfortunately, Sets only enforce uniqueness for primitive values, but our list is full of objects.
Instead, we can do something like this.
const list = [
{ name: 'John' },
{ name: 'Sara' },
{ name: 'Sara' },
{ name: 'Lynn' },
{ name: 'Jake' }
];
const map = new Map();
list.forEach(item => {
map.set(item.name, item)
});
const uniqueList = Array.from(map.values())
Notice we’re using a Map here. Since Map’s preserve insertion order, our uniqueList will have the same order as the original list, but without the duplicates since we’re using name as the key.