The Set object and how it works

Published 4 months ago

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

Conclusion

Do you need a data container to store unique values? Give Set a try 😎

Sets don't have any built-in methods to retrieve the index of a value even though they are classed as an iterable. You'll need to convert a Set into an array to achieve this. It's the same process if you'd like to sort a Set object - convert it to an array and then use the arrays sort method.

Overall I don't think Sets have a great advantage over arrays or objects for storing data but they seem like a great option to have if we quickly need to store some unique values without having to do any heavy lifting.

Set.prototype​.add() // add to a Set
Set.prototype​.clear() // Empty a Set
Set.prototype​.delete() // delete entries in a Set
Set.prototype​.for​Each() // loop over a Set
Set.prototype​.has() // Check if a value exists in a Set

Creating a Set

const me = new Set();
// => {}

const numbers = new Set([1, 2, 3, 4, 5]);
// => { 1, 2, 3, 4, 5 }

How can we use it?

Lets remove duplicates from an array:

This is one of my recent discoveries when using the Set object.

const numbers = [1, 1, 1, 2, 3, 4, 4, 4, 5];

const strings = ["andy", "andy", "coupe", "javascript", "javascript"];

const duplicateNumbersRemoved = [...new Set(numbers)];
// => [1, 2, 3, 4, 5]

const duplicateStringsRemoved = [...new Set(strings)];
// => ["andy", "coupe", "javascript"]

Add a value to a Set:

You can add multiple values to a Set by calling add() multiple times.

const numbers = new Set();

numbers.add(1);
numbers.add(2);
numbers.add(3);

console.log(numbers);
// => { 1, 2, 3 }

Remove a value from a Set:

const numbers = new Set([1, 2, 3]);

numbers.delete(2);
// => returns true if found

console.log(numbers);
// => { 1, 3 }

Check if a value exists in a Set:

const numbers = new Set([1, 2, 3]);

numbers.has(2);
// => returns true

numbers.has(5);
// => returns false

Empty the Set:

const numbers = new Set([1, 2, 3]);

numbers.clear();

console.log(numbers);
// => { }

Convert a Set to an array:

const numbers = new Set([1, 2, 3]);

Array.from(numbers);
// => [1, 2, 3]

const setToArray = [...numbers];
// => [1, 2, 3]