Set in ES6 Javascript with example

JavaScript

In this post we are going to learn about JavaScript Set in ES6(2015) with examples.

What is Set in JavaScript ES6?

A set object is a unique values collection of a different datatype which includes the primitive type or complex object literal, Array.It makes us iterate the elements in insertion order.

Syntax

new set([iterable]);

Parameters

  • iterable(optional):-This is optional parameter.

Return Value:

It returns a new set of Object

How to create a JS Set and assign values?

Let us understand this with an example of how we can create a Set and assign some values to this set. Here in this example, we are creating a set object and passing an array as iterable.

let  setObject = new Set(['JS','Rust']);
console.log(setObject)

Output

Set { 'JS', 'Rust' }

How to use Set Size Property?

This set property returns an integer value as the number of elements in the Set. Let us jump into the Example. We have two elements in the set, so when we are using the “size” property, It returns the size of the set as 2.

let  setObject = new Set(['JS','Rust']);
console.log(setObject.size)

Output

size of set = 2

All methods of JS ES6 Set


These are the Set object instance method.

  • Add():-This method adds an item with a specified value at end of the Set object.
  • Has():-This Method checks if the item with the value exists in Set Object, and return true if exist else return false.
  • Delete(): This method deletes an item related to value, from the Set object and returns true or false.
  • Clear():-This method cleans the Set object and removes all items of the Set object.

Let us understand all methods with examples.

Set add() Method : How to Add Item in Set

We can use JavaScript set Add() method to add elements in set.

  • First, we are creating an object(setobj) of JS set.
  • adding elements to JS Set one by one by one
  • Printing all the added element
let setObj = new Set()

//adding items in set
setObj.add('C#')           
setObj.add('React')           
setObj.add('Go')           
setObj.add(1)
console.log('added item in Set:');
console.log(setObj)

Output

added items in Set:
Set { 'C#', 'React', 'Go', 1 }

How to Add multiple items in JS Set

We can add multiple items to Set by passing an array as iterable. Let us jump into the example

let setObj = new Set(['C#','React','Go'])
console.log(setObj)

Output

Set { 'C#', 'React', 'Go' }

Set has() Method: How to check item exist in Set

In this example we are checking if item exist in the Set.Item “C#” exist in the Set, So we are getting “true” as output.

let setObj = new Set()

//adding items in set
setObj.add('C#')           
setObj.add('React')           
setObj.add('Go')           
setObj.add(1)
console.log('item exist in Set = '+setObj.has('C#'))

Output

item exist in Set = true

Set Delete() method: How to Delete an item from JS Set

Here we are deleting item ‘React’ from the Set and printing the Set after deleting ‘React’ item.

let setObj = new Set()

//adding items in set
setObj.add('C#')           
setObj.add('React')           
setObj.add('Go')           
setObj.add(1)
setObj.delete('React')
console.log('Set after deleting the item =')
console.log(setObj)

Output

Set after deleting the item =
Set { 'C#', 'Go', 1 }

Set clear() method : How to Remove all Items of JS Set

In this example we are removing all items of Set by calling the clear() method.

let setObj = new Set()

//adding items in set
setObj.add('C#')           
setObj.add('React')           
setObj.add('Go')           
setObj.add(1)
setObj.clear() //all items are remove from the Set Object

How to loop over the JS Set


These are list of ways we can use to loop over the JS Set

  • Set.values()
  • Set.Keys()
  • Set.entries()
  • Foreach loop

1. Loop over the JS Set values

Set.values() : This method return an iterator object over each value of Set

let setObj = new Set(['C#','React','Go'])
let iterator = setObj.values();
for(val of iterator)
{
console.log(val)
}

Output

C#
React
Go

2. Loop over the JS Set keys

Set.Keys(): This method return an iterator object over each value of Set.

let setObj = new Set(['C#','React','Go'])
let iterator = setObj.keys();
for(val of iterator)
{
console.log(val)
}

Output

C#
React
Go

3.Loop over the JS Set keys-values

Set.entries(): This method return an array of [value,value] of each item in Set.The Set does have keys, So when we iterating using entries() method it return values of item as key as well as value.

Let us understand with example.

let setObj = new Set(['C#','React','Go'])
let iterator = setObj.entries();
for(val of iterator)
{
console.log(val)
}

Output

[ 'C#', 'C#' ]
[ 'React', 'React' ]
[ 'Go', 'Go' ]

4. How to use For-each loop with JS Set

A callback function gets called for each item of Set object in insertion order.Here, We are calling setElement() function for each item of Set and printing items.

function setElement(v1, v2, setObj) {
  console.log(`[${v1}] = ${v2}`);
}
let setObj = new Set(['C#','React','Go']).forEach(setElement)

Output

[C#] = C#
[React] = React
[Go] = Go

What is JS WeakSet?

WeakSet object is a unique collection of objects that do not contain other datatypes.WeakSet values are automatically Garbage collected.WeakSet does not have a size property. It is rarely used in implementations.

Different between Set and WeakSet

  • WeakSet is a unique collection of objects only, whereas Set is a collection of any datatype Primitives as well as complex data types.
  • We can iterate over Set, But not on WeakSet.
  • Set has size property, whereas WeakSet does not have size.

Some examples using Set

Remove Duplicate Element from Array

const lang = ['C#','C#','JS','React','JS','React']

console.log([...new Set(lang)]) 

Output

[ 'C#', 'JS', 'React' ]

Set with String Example

let str = 'String'

let StrSet = new Set(str)  

console.log(StrSet.size)
new Set("SetExmple")

Output

6
Set { 'S', 'e', 't', 'E', 'x', 'm', 'p', 'l' }