Creating a Set using Javascript


Let's create a MySet class so that it doesn't hide the actual set class in JS. We'll create a container object that'll keep track of all our values that we add to the set. We'll also create a display function that prints the set for us. 

Example

class MySet {
   constructor() {
      this.container = {};
   }
   display() {
      console.log(this.container);
   }
}

In ES6, you can directly create a set using the Set class. For example, 

Example

const set1 = new Set();
const set2 = new Set([1, 2, 5, 6]);

Checking for membership

The has method checks if a value exists in the set or not. We'll use the Object.hasOwnProperty method to check it in the container. For example, 

Example

has(val) {
   return this.container.hasOwnProperty(val);
}

In ES6 Sets, you can use this directly − 

Example

const testSet = new Set([1, 2, 5, 6]);
console.log(testSet.has(5));
console.log(testSet.has(20));
console.log(testSet.has(1));

Output

This will give the output −

True
False
True

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 15-Jun-2020

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements