2
33

JavaScript: How to create and use JavaScript Set

Reading Time: 2 minutes

We can create JavaScript Set whenever there is a need to store a set of unique values, it is a built-in object since ES6 that store objects or references uniquely. Here, let’s explore how to use this built-in object.

Advantages of using a Set

There are several advantages in using Set. Here are some of them.

  • Easy storage of unique values
  • Faster checking for previously added values

Various Key DataType Supported

  • Primitive
  • Function
  • Objects

How to create and use JavaScript Set

Pre ES6 Style

Prior to ES6, we can create a Set by using an array. However, this method needs addition code to perform checking for duplicate.

Below shows the illustration of creating and iterating a Set prior to ES6. As this example is only apply to string array, there will be more complex logic possibly for other datatype.

// Create a array with unique values
var nameSet = ['Person1', 'Person2', 'Person3'];

// Method to check if 
function checkDuplicates(nameSet, value) {
  for(var i = 0; i < nameSet.length; i++) {
    if (nameSet[i] === value) {
      return true;
    }
  }
  return false;
}

// Perform insertion if no duplicates
if (!checkDuplicates(nameSet, 'Person4')) {
  nameSet.push('Person4');
}

ES6 Style

With the introduction of Set datatype, it has become easier for developer to perform operation like create, insert and delete on Set.

In the below illustration, we will show how to create and store various datatype into Set. Also, how to delete and retrieve them.

const nameSet = new Set();

let person1 = { name: "Person1" };
let person2 = "Person1";
let person3 = 1000;

// Set different type of values
nameSet.add(person1);
nameSet.add(person2);
nameSet.add(person3);

// Validate that they exist
console.log(nameSet.has(person1));  
console.log(nameSet.has("Person1"));
console.log(nameSet.has(1000));

// Delete age via key
nameSet.delete('Person1');

// Check how many value in the set
console.log(nameSet.size);  // 2

Related Operation on Set

There are also other useful operations that we have discuss in this blog.

Conclusion

Although there are other common data structure like array, JavaScript Set is much more easy to use without the need to take care of comparison logic.

For other examples, can refer to MDN documentation here.

Show Comments

No Responses Yet

Leave a Reply