Sets in JavaScript
In JavaScript, a set is a list-like structure containing unique values, which can be primitives and/or object references. Unlike an array, a set's elements cannot be accessed by index.
A value cannot be added to a set if it is strictly equal to any of the set's elements.
const set = new Set();
const object = { color: 'lime green' };
const functionallyIdenticalObject = { color: 'lime green' };
set.add(object);
set.add('wow');
set.add(77);
console.log(set.size);
//=> 3
set.add(functionallyIdenticalObject); // added because functionallyIdenticalObject is not strictly equal to object
console.log(set.size);
//=> 4
set.add(77); // not added because 77 is strictly equal to 77
console.log(set.size);
//=> 4
You can provide an array as an argument when creating a set, and the array's values will become the values of the set, also removing the duplicate values.
const array = [1, 5, 4, 1];
const set = new Set(array); // the set's values become [1, 5, 4]
console.log(set.size);
//=> 3
To convert a set to an array, you can use Array.from(), which converts an iterable such as a set or a map to an array.
const set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
const array = Array.from(set);
console.log(array);
//=> [1, 2, 3, 4]
To check whether a set has some values or not, we use has method
const set1 = new Set([1, 2, 3, 4, 5]);
console.log(set1.has(1));
// true
console.log(set1.has(5));
// true
console.log(set1.has(6));
// false
To delete any value from the set, we use delete method
const mySet = new Set();
mySet.add("foo");
console.log(mySet.delete("bar"));
// false; no "bar" element found to be deleted.
console.log(mySet.delete("foo"));
// true; successfully removed.
console.log(mySet.has("foo"));
// false; the "foo" element is no longer present.
Credits: Exercism
Subscribe to my newsletter
Read articles from Zeeshan Safdar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Zeeshan Safdar
Zeeshan Safdar
An accomplished front-end developer with a strong background in creating visually stunning and user-friendly websites and web applications. My deep understanding of web development principles and user-centered design allows me to deliver projects that exceed client expectations. I have a proven track record of success in delivering projects on time and to the highest standards, and I am able to work well in a team environment and am always looking for new challenges to take on.