This page looks best with JavaScript enabled

Use Set in Javascript

 ·   ·  ☕ 4 min read

Set was introduced in ES6 and is a collection of values without keys. It has one killer feature that you want to use - filtering duplicates owing to its feature of allowing only unique values.

So.. set?

People from other languages may be familiar with sets, maps and arrays.. and the confusion that comes with them.

  • What is a set (map, or array)?
  • Why should I use it?
  • When should I use what?
  • How is it different?
  • Why am I alive?
  • What is the purpose of life?

As a Javascript developer, I was immune to that - use arrays for series of elements, objects for rest (aka keyed elements).

Except - if you want to avoid duplicates easily, or not iterate whenever you want specific elements - then you definitely want to use objects. And oh.. I completely ignore maps - because I can. And also because I (probably unconsciously) avoid situations that requires weird keys.

Sorry.. getting back to the drawing board - set.

As I was saying Sets are introduced in ES6. They can be treated as ‘special’ type of collections that support typical collection operations.

Create set and add elements

Just like its collection management cousins, set is initiated and used quite easily.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const planets = new Set();

planets.add("mercury");
planets.add("venus");
planets.add("earth");
console.log("planets: ", planets);

/* output
planets:  Set { 'mercury', 'venus', 'earth' }
*/

However, adding same elements will not yield any changes in the set.

1
2
3
4
5
6
const planets = new Set();

planets.add("mercury");
planets.add("earth");
planets.add("earth");
console.log("planets: ", planets); // Set { 'mercury', 'earth' }

The behaviour in a set of objects is slightly more complicated. The below code where you add the exact object will avoid the duplicates.

1
2
3
4
5
6
const planets = new Set();

const earth = { name: "earth", position: 3 };
planets.add(earth);
planets.add(earth);
console.log("planets: ", planets); // Set { { name: 'earth', position: 3 } }

However the below code will take in everything.

1
2
3
4
5
const planets = new Set();
planets.add({ name: "earth", position: 3 });
planets.add({ name: "earth", position: 3 });
console.log("planets: ", planets);
// Set { { name: 'earth', position: 3 }, { name: 'earth', position: 3 } }

Duplicate objects like these are allowed because set determined object uniqueness by reference and not value.

Iterating a set

Use a for/of, or forEach.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const planets = new Set();

planets.add("mercury");
planets.add("venus");
planets.add("earth");

//console.log("planets: ", planets);
planets.forEach((planet) => console.log(planet));
/* output
mercury
venus
earth
*/

Deleting stuff

Remove an element from set.

1
2
console.log(planets.delete("earth")); // true
console.log("planets: ", planets); // Set { 'mercury', 'venus' }

Clear everything out.

1
2
planets.clear();
console.log("planets: ", planets); // Set {}

Other Cool Features

How many elements are plonked in the set so far?

1
console.log(planets.size); // 3

Check whether a value already exists.

1
console.log(planets.has("earth")); // true

Why should you use set?

  • Two words - avoid duplicates.
    Set does not need loops to catch duplicates.

  • Has a fast has function to determine whether set has a particular element

Why you may not like sets?

  • Object deduplication is by reference. That seldom happens in the real world - why would I add the same object again in my own logic?

  • I can get the same done in objects - no problem (need no loop, silently fail for duplicates). It has the added advantage of enabling custom logic to avoid duplicates for objects

  • There is no order or an index. I don’t expect anyone to cry on this since sets across languages are purpose built this way. You would have to convert to another collection like an array for indexes (and if you are doing it, are you sure you wanted to begin with a set in the first place?)

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things