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
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);
Output
Just three words to describe it. Simple, concise and awesome. No more loops while searching and eliminating duplicates. Its a simple one line code solution.