Sets in Javascript
The set object lets you store unique values of any type, whether primitive values or object references.
Let’s talk about the fact that we have a series of numbers and that we don’t want repeated values, we just want unique values.
let numbers = [1, 25, 33, 1, 54, 3, 2, 15];
How do you remove the duplicates, we have a few options:
Foreach()
function removeDuplicates(numbers) {
let unique = {};
numbers.forEach(number => {
if (!unique[number]) {
unique[number] = true;
}
});
return Object.keys(unique);
}console.log(removeDuplicates(numbers));// [ '1', '2', '3', '15', '25', '33', '54' ]
Filter()
let numbers = [1, 25, 33, 1, 54, 3, 2, 15];let newNumbers = numbers.filter((number, index) => {
return numbers.indexOf(number) === index;
});console.log(newNumbers);// [ 1, 25, 33, 54, 3, 2, 15 ]
But the most simple option is,
new Set( [iterable] );
This object have one argument (iterable)
iterable -> Optional. If an iterable object is passed, all of its elements will be added to the new Set
. If you don't specify this parameter, or its value is null
, the new Set
is empty.
Let´s remove the duplicates with Set Object and also convert the set into an array:
let numbers = [1, 25, 33, 1, 54, 3, 2, 15];let numbersWithoutDuplicates = new Set(numbers);console.log(Array.from(numbersWithoutDuplicates));// [ 1, 25, 33, 54, 3, 2, 15 ]