Removing duplicates from an array with the vanilla JS Set() object
Last year, I wrote about how to remove duplicates from an array in vanilla JS using the Array.filter() and indexOf() methods.
var sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];
var deduped = sandwiches.filter(function (sandwich, index) {
return sandwiches.indexOf(sandwich) === index;
});
// Logs ["turkey", "ham", "tuna", "pb&j"]
console.log(deduped);
But last week, Samantha Ming taught me a really cool way to do the same thing using the new Set() constructor.
Setis a new data object introduced in ES6. BecauseSetonly lets you store unique values. When you pass in an array, it will remove any duplicate values.
Looking at our previous example, we would pass the sandwiches array into a Set() constructor, and then use Array.from() to convert it back into an array (Samantha favors the destructuring method: [...]).
var sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];
var deduped = Array.from(new Set(sandwiches));
// Logs ["turkey", "ham", "tuna", "pb&j"]
console.log(deduped);
It’s so neat and clean and simple. I love it!
What’s browser compatibility look like? This approach works in all modern browsers, but doesn’t support IE (both new Set() with an array and Array.from() don’t work in IE).
Important! Polyfill.io was sold to a new owner based in China, and is now injecting malware onto sites that use it. DO NOT use it on any site for any reason.
The good news, at least: polyfill.io has a polyfill for it. Just be aware that it’s not part of the default build, so you’ll need to add it.
Also, Samantha’s website is full of JS goodness. Go check it out!