DEV Community

Cover image for JS Set Object (2 handy usages)
Dimitris Chitas
Dimitris Chitas

Posted on • Edited on

JS Set Object (2 handy usages)

Hello there guys.

Today i will talk for the SET object which is storing new
unique values of any type as well primitive values and object references.
This could be handy for some cases,i will show you two of them
in this thread.

Cases

  1. Remove duplicated records from the arrays
  2. Using add() method to add values to the SET object

So first lets create our array and try our first case,in my example we will set some values twice,with this way we will see
how Set() will help us to point and delete the overwrites.

let myArray = ['Jim','Jhon','Grace','Felice','Jhon','Sylia','Grace'] ;

let myArrayClear = [...new Set(myArray)]
console.log(myArrayClear)

Enter fullscreen mode Exit fullscreen mode

The result without double records.
image

Check to see the results on your console it should miss the double records,job done!

Secondary we will see how a new instance of Set object could work very nicely with add() method and create values as long as avoiding the double records, let's take a look.

const mySetObject = new Set()

mySetObject.add(2)
mySetObject.add('Hello Word')
mySetObject.add(4)
mySetObject.add({a: 1, b: 2})
mySetObject.add(2)


Enter fullscreen mode Exit fullscreen mode

After our additions (number,string,object) we can itterate through our array that contains different values and data types but you will notice that we add the number 2 twice,whe we will loop though and you will see that is beeing added only once because of the rule "A value in the Set may only occur once".So let's use for to see what we get.

const mySetObject = new Set()

mySetObject.add(2)
mySetObject.add('Hello Word')
mySetObject.add(4)
mySetObject.add({a: 1, b: 2})
mySetObject.add(2)

for (let item of mySetObject) console.log(item)

Enter fullscreen mode Exit fullscreen mode

image

That's all for today!

Have a nice workday guys, in case for further explanation do not hesitate to contact me or find me in github or linkedin.
GitHub : https://github.com/feco2019
Linkedin : https://www.linkedin.com/in/dimitris-chitas-930285191/

Top comments (0)