Remove Duplicates in a JavaScript Array using ES6 Set and from() Function

ES6 or ECMAScript 6 has many useful features and two of its features recently got my attention. We use Arrays in JavaScript and often come across duplicates. Traditionally, to get rid these unwanted duplicates, we would iterate through each value in the array, extract unique values and add the values in another array. ES6 has now made it simple. Using its Set data structure along the from() function of Array object, you can easily remove duplicates in a JavaScript array.

Here’s an example.

const num = [5, 2, 3, 4, 9, 3, 5];
const unique_numbers = Array.from(new Set(num));



Remove Duplicates in JavaScript Array using ES6 Set and from()

Browser Support:
Chrome 39.0 - Yes | Firefox 34.0+ - Yes | Internet Explorer 10 - No | Safari 5.1 - No

I have an array of numbers. As you can see from the above example, numbers 3 and 5 are defined twice.

Using new Set(), I am first removing the duplicates. Sets in ES6 are iterable and it maintains the original order. If you run your app using only new Set, you get this in your browser console.

Set (5) {5, 2, 3, 4, 9}

However, I want it in an array again. Therefore, I am using the from() function of the Array object to convert it back to an array.

Array.from (new Set(num));

This is not restricted to just numbers. You can remove duplicates from an array of string values. For example,

const colors = ['blue', 'green', 'purple', 'blue', 'red'];
const unique_colors = Array.from(new Set(colors));



Remove Duplicates in JavaScript Array using ES6


Just three words to describe it. Simple, Concise and Awesome. No more loops while searching and eliminating duplicates. A simple line code and that is it.

Thanks for reading.

Previous - Dynamically Create Checkboxes based on Textbox Values using JavaScriptNext - Change Label Text on Button Click using JavaScript or jQuery

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!