DEV Community

Sneh Mehta
Sneh Mehta

Posted on

1

Set - Unique values collection javascript way

Background before we dive in:
Recently, I came across a problem where I had to load images from a third party server using ids given to me. Calling an API to load those images would be an expensive operation since size of the image varied and was unpredictable. Additionally, list of ids had duplications.

Set to the rescue:
I wasn't aware of an easy way to create list of unique values in javascript and decided to pursue that knowledge.

Set is an object which lets you store unique values of any type.

let mySet = new Set();

mySet.add('a1s2d3');
//['a1s2d3']

mySet.add('z4t6h8');
//['a1s2d3', 'z4t6h8']

mySet.add('a1s2d3');
//['a1s2d3', 'z4t6h8']

It prevents duplication when you try to add same value again. This was the best way to solve my problem.

It works even in a situation with more complex objects.

You can follow a detailed documentation on MDN Website. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set


This is my first dev.to post! I appreciate your time reading this. Any feedback is welcome.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up