Let’s imagine you had an array of
sandwiches, and some of the items in it were listed more than once.
let sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];
You want to get an updated list with the duplicates removed, a process called deduplication.
This used to require pairing the
Array.filter() method with
Array.indexOf(). And while that method still works, today, it’s a bit simpler to use
Array.from() with the
new Set() constructor creates an iterable collection of items, just like an array. But, each item can only be included once.
To remove any duplicates, we can pass our array into the
new Set() constructor, then convert the returned collection back into an array.
let deduped = Array.from(new Set(sandwiches));
If you’d prefer, you can use the spread syntax instead of
let deduped = [...new Set(sandwiches)];