Use-Cases of this Tutorial
There are many ways of removing duplicate entries from an array, however using the Set data type to do so is the most simplest way — it will consume the least amount of code. Also because Sets are a built-in feature, we can be sure that it will give bug-free results.
So to eliminate duplicates from an array we can follow this process :
- Initialize a Set from the given array.
- The Set will automatically remove the duplicates.
- Get the elements of the Set returned as an array.
Initializing Set from an Array
A Set can be initialized with any iterable object — any object that can be looped using a for..of statement. Obviously arrays can be looped through using this.
var arr = [1, 2, 3, 4, 5, 4, 3, 56, 2, 56, 1, 7, 7]; // initialize Set from an array var set_ob = new Set(arr);
Creating the Set has automatically eliminated all duplicates. However this is a Set data type, we will need as an array data type.
Set to an Array using the Spread Operator
The Spread operator represented by three dots ... expands a given iterable object. A Set is also an iterable object (it can be looped using for..of).
Spread operator gets individual elements from the Set. We can then initialize a new array from these individual elements.
Below are the final codes to remove duplicates from an array :
// given array var arr = [1, 2, 3, 4, 5, 4, 3, 56, 2, 56, 1, 7, 7]; // new Set var set_ob = new Set(arr); // new array using spread operator on Set var new_arr = [ ...set_ob ]; // [ 1, 2, 3, 4, 5, 56, 7 ] console.log(new_arr);