Introduction

The set object lets you store unique values of any type, whether primitive values or object references.

The problem

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:

Solutions

Foreach()

function removeDuplicates(numbers) {

let unique = {};

numbers.forEach(number => {

if (!unique[number]) {

unique[number] = true;

}

});

return Object.keys(unique);

} console.log(removeDuplicates(numbers)); // Output [ '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); // Output [ 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)); // Output [ 1, 25, 33, 54, 3, 2, 15 ]

Conclusion

Arrays must be the default option for every programmer because they have enough methods to handle data sets.

Instead, sets must be used when dealing with different or unique elements in a data set.