JavaScript - Remove duplicates from array using ES6 Set and from()

← PrevNext →

ES6 or ECMAScript 6 has many useful features and two of its features recently got my attention. We use Array in JavaScript and often come across duplicates values. Traditionally, to get rid these unwanted duplicates we use code to 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 with the from() function of array object, you can easily remove duplicates from an array.

Here’s an example.

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

console.log(num);
console.log(unique_numbers);

Output

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

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 too. For example,

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

console.log(colors);
console.log(unique_colors);
Try it

Image of the result

Remove Duplicates in JavaScript Array using ES6

Conclusion

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

Thanks for reading. 🙂

← PreviousNext →