Skip to main content Accessibility Feedback

How to remove duplicates from an array with vanilla JS

Today, we’re going to learn how to remove duplicates from an array in JavaScript.

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 Set() object.

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));

Here’s a demo.

If you’d prefer, you can use the spread syntax instead of Array.from().

let deduped = [ Set(sandwiches)];

I’ve put together a helper function you can use if you’d like.