var index = [0,0,2,2]
var uniq = [...new Set(index)];
console.log(uniq) //[0,2]
This code removes duplicated entries of the array, I do not understand how the …new and set work together to achieve this
var index = [0,0,2,2]
var uniq = [...new Set(index)];
console.log(uniq) //[0,2]
This code removes duplicated entries of the array, I do not understand how the …new and set work together to achieve this
That’s the Set object, which is relatively new in JS:
You create a new Set using the new
operator. You can pass the constructor an array and it will automatically add the elements in the array to the Set. Since items in a Set must be unique the duplicates in the array are automatically removed.
A Set is a data structure in JS, it’s find of like an array but no duplicate values are allowed. So, new Set(index)
creates a set out of your data (removing the duplicates). Then, spreading them out coverts them back to an array.
You can think of it this way:
var index = [0,0,2,2]
var nonDuplicateSet = new Set(index);
var nonDuplicateArray = [...nonDuplicateSet];
var uniq = nonDuplicateArray;
console.log(uniq) //[0,2]