JavaScript Set object to store unique values

The Set in JavaScript is a special type of object which lets us store unique values. It works for values of both primitive and non-primitive data types.

When it comes to storing a bunch of data, we can always go for Arrays. But if we want to store unique values, Set is a better option when compared to the Array. Though in the Array, we can manually filter out all the duplicate values, or we can check if the value already exists beforehand while adding to the collection.

const set = new Set();

The Set() constructor creates a new Set object. This constructor also accepts an optional argument that must be iterable. If we pass any argument, it will filter out all the non-duplicate values and add them to the new Set. But if we don’t pass one, the Set will be empty.      

Some examples of built-in iterables are Array, Map, String, Generators, etc.

const set1 = new Set();
console.log(set1); // Set(0) {size: 0}

const set2 = new Set([2, 'x', 5, true, 2, 'x', true, 6]);
console.log(set2); // Set(5) {2, 'x', 5, true, 6}

// checking for String
const set3 = new Set('world');
console.log(set3); // Set(5) {'w', 'o', 'r', 'l', 'd'}

// String with duplicate characters
const set4 = new Set('madam');
console.log(set4); // Set(3) {'m', 'a', 'd'}

Utility methods and property

The Set object provides a couple of helper methods that we can use to add/delete values or check if any value exists and many more. Let’s find them all.

The add() method

This method adds value to the end of the Set object. If the value is already present in the Set, it won’t add it. This method returns the updated Set object.

const set = new Set();
set.add(10); // Set(1) {10}
set.add('Hello'); // Set(2) {10, 'Hello'}
set.add(10); // Set(2) {10, 'Hello'}
set.add(20); // Set(3) {10, 'Hello', 20}
set.add('Hello'); // Set(3) {10, 'Hello', 20}

When we add non-primitive values, Set tests their uniqueness by their references and not by their values. Let’s see one example.

const ob1 = { x: 2 };
const ob2 = ob1;
const ob3 = { x: 2 };

const set = new Set();
set.add(ob1); // Set(1) {{...}}
set.add(ob2); // Set(1) {{...}}
set.add(ob3); // Set(2) {{...}, {...}}

Here ob1 and ob2 are referencing the same object, so Set treated ob2 as duplicate and didn’t add it. On the other hand, ob3 has the same value as ob1 and ob2, but it is referencing a different object, so Set treated it as unique and added it.

The Set considers all NaN values as same, though NaN !== NaN.

The add() method is chainable.

const set = new Set();
set.add(8).add(null).add("Hello").add(NaN).add();
// Set(5) {8, null, 'Hello', NaN, undefined}
set.add(NaN).add(undefined).add(null).add(false);
// Set(6) {8, null, 'Hello', NaN, undefined, false}

The delete() method

This method removes the value from the Set. It takes the value as the argument that we want to remove from Set. If the passed value is present in the Set, delete() removes it and returns true otherwise, it returns false.

const set = new Set();
set.add(8); // Set(1) {8}
set.add('Hello'); // Set(2) {8, 'Hello'}
set.delete(8); // true
set.delete('world'); // false
console.log(set); // Set(1) {'Hello'}

The has() method

This method checks whether a value is present in the Set or not. If the value exists, it returns true otherwise returns false.

const set = new Set();
set.add('Hello'); // Set(1) {'Hello'}
set.add(8); // Set(2) {'Hello', 8}
set.delete('Hello'); // Set(1) {8}
console.log(set.has(8)); // true
console.log(set.has('Hello')); // false

The clear() method

This method removes all the values present in the Set object.

const set = new Set([2, "x", true, 10]);
set.clear();
console.log(set); // Set(0) {size: 0}

The size property

This property returns the number of values present in the Set object.

const set = new Set([2, "x", 2, 5]);
console.log(set.size); // 3

The forEach() method()

This method loops through the Set values and calls the provided callback function for each value.

const set = new Set();
set.add(5).add(8).add(2); // Set(3) {5, 8, 2}
set.forEach((value) => {
  console.log(value);
});
/*
5
8
2
*/

We can also use the for…of loop to iterate over Set.

const set = new Set();
set.add(5).add(8).add(2); // Set(3) {5, 8, 2}
for (const value of set) {
  console.log(value);
}
/*
5
8
2
*/

Converting Set into Array

There are many ways to convert a Set into an Array, but we will only discuss the easiest and convenient ones. As we know, the Set is iterable, we can use the spread operator or Array.from() method to create an array from the Set.

const set = new Set();
set.add(5).add(10).add('Hello'); // Set(3) {5, 10, 'Hello'}
const arr1 = [...set];
const arr2 = Array.from(set);
console.log(arr1); // [5, 10, 'Hello']
console.log(arr2); // [5, 10, 'Hello']

Removing duplicates from Array using Set

To remove duplicates from Array using Set, first, we can create a Set object from Array and then convert the Set back to Array.

const arr = [10, 5, 20, 10, 6, 5, 8, 5, 20];
const set = new Set(arr);
const newArr = [...set];
console.log(newArr); // [10, 5, 20, 6, 8]

// shorthand
console.log([...new Set(arr)]);

See Next

Map in JavaScript and when it’s a better choice than Object

Leave a Reply

Your email address will not be published. Required fields are marked *