Using Set in JavaScript

What is Set in JavaScript?

Set lets you store unique object references or primitive values.

Let’s start with an example:

1. Using primitive values

const numbers = new Set([1,2,3,3]);
for(let number of numbers) {
  console.log(number ); 
}
//1
//2
//3
const strings = new Set(['1','2','3','3']);
for(let string of strings) {
  console.log(string ); 
}
//'1'
//'2'
//'3'

What we illustrated above is just a simple usecase where we have primitive values and we need those values to be unique, creating a set is the simplest way to do it.

In the next example we will look at how we can make a set with unique objects references:

2. Using object references

const person = {
  name: 'Allan'
};
const person2 = {
  name: 'Jhon'
};
const persons = new Set([person, person, person, person2]);
for(let person of persons) {
  console.log(person.name); 
}
//"Allan"
//"Jhon"

As you might seen we’ve created a new set with 4 persons, but the object was the same (reference) and therefor it was removed from our collection.

In the last example we will look at how we can make a collection of unique objects based on a particular property that all objects are sharing:

3. Unique objects based on a property name

const person = {
  name: 'Allan'
};
const person2 = {
  name: 'Allan'
};
const person3 = {
  name: 'Jhon'
};
const persons = [person, person, person, person2, person3, person3];

const uniqByName = [];
const tempSet = new Set();
for (const person of persons) {
    if(!tempSet.has(person.name)){
        tempSet.add(person.name);
        uniqByName.push({
            name: person.name
        });
    }
}

console.log(uniqByName);
//[[object Object] {
  name: "Allan"
}, [object Object] {
  name: "Jhon"
}]

Using the Set object we were able to build a much more nicer and cleaner way to create an array with unique object based on some random property.

Read more on sets here.

Get The Best Of All Posts Delivered To Your Inbox

Subscribe to our newsletter and stay updated.