DEV Community

Cover image for JavaScript - Set
Tanwa Sripan
Tanwa Sripan

Posted on

JavaScript - Set

I am currently partaking in the #100DaysOfCode challenge, and everyday I try to solve one Data Structure and Algorithm problem using JavaScript. I have encountered Set and Map and I want to talk a little a bit about the Set object type.

Set

The Set object type was introduced with ECMAScript 2015 (or ES6) which allow you to store all kind of JavaScript data types as a unique set of elements. It is very similar to an Array in JavaScript but it has other syntax that allows you to access, check, and delete elements in the Set. This particular object type comes with its own methods, in particular, the .has() method which allows you to check for elements inside the Set much like Array.prototype.includes, and according to the MDN Docs it is quicker than .includes on average.

The methods that we can use with Set object type are .add(), .clear(), .delete(), and .has(). It also has a property .size which is similar to Array.prototype.length.

Example: Let's look at some of the Set methods.


const twiceTwice = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5];

const uniqueNumbers = new Set(twiceTwice);

console.log(uniqueNumbers) // { 1, 2, 3, 4, 5 };

// can add new elements, any data type
uniqueNumbers.add("Rasengan");
uniqueNumbers.add({name: "Tanwa", favouriteColor: "Red"});
console.log(uniqueNumbers);
/* Set(7) {1, 2, 3, 4, 5, …}
[[Entries]]
0: 1
1: 2
2: 3
3: 4
4: 5
5: "Rasengan"
6:
value: {name: 'Tanwa', favouriteColor: 'Red'}
size: 7 */

// check for an element
uniqueNumbers.has("Rasengan"); // True

// delete an element
uniqueNumbers.delete(2); // True

// check size
uniqueNumbers.size; // 6

// clear
uniqueNumbers.clear();


Enter fullscreen mode Exit fullscreen mode

Example use case

To solve 3. Longest Substring Without Repeating Characters on leetcode, I used Set to form and store the substring as I iterate through the string using two pointers, and each iteration, checking the Set using .has() to see if the element already exist before using .add() to append new values or .delete() to remove the element starting from the left. You can see my solution on my website.

Summary

Set is an object type that allows you to store unique elements of any type. And these are the methods:

  • .add(): you can add a new element to the end of the Set. Returns the new Set.
  • .clear(): you can remove all the elements in the Set.
  • .delete(): you can remove a specific value from the Set. Returns false if an element is not in the Set. Returns true for successfully removing the element.
  • .has(): you can check if an element is in the Set. Returns a Boolean.

Next time you need to remove a specific element from a unique set of values, you can try using Set and its methods.

Thank you for reading, I hope you found it useful. Please leave comments and feedbacks if you have them :)
Anime character MHA Todoroki

Top comments (0)