JavaScript Map and Set

Table of contents

Set:-

a set object is a collection of unique data. In set we can only store the unique value. Values will store in the insertion order so we can iterate over the set for getting the element in the insertion order.

Syntax:

const mySet = new Set();

We can also create the constructor of a set with help of the new Set() keyword.

Methods of set:

set.add()
set.clear()
set.delete()
set.forEach()
set.has()
set.Enteries()
set.keys()
set.values()
etc.....

Example code of set:-


const mySet = new Set()
mySet.add(12)
mySet.add(32)
mySet.add(78)
mySet.add(20)

console.log(mySet.has(12))
console.log(mySet.values());

 console.log(mySet.entries())
console.log(mySet.size)
 mySet.forEach(element => {
     console.log(element)
 });

const myArray = [23,53,75,27,90]
 const newSet = new Set([...myArray])
newSet.forEach(element => {
    console.log(element)
});
newSet.clear()
console.log(newSet)
console.log(newSet)
console.log(newSet.size)

function setDifference (setA , setB)
{

    return new Set([...setA].filter(ele=> setB.has(ele)))
}
const SetA = [12,32,42,43,89]
const SetB = [89, 90, 42, 78]
const result = setDifference(SetA, SetB)
console.log(result)

Map:-

map objects are the collection of key-value pairs. The key value of the map should be unique. Any type of value can be used as a key or value in a map object. we can iterate the value of the map with the help of key value.

syntax:-

const myMap = new Map();

Methods of the map:-

myMap.clear()
myMap.delete()
myMap.enteries()
myMap.forEach()
myMap.get()
myMap.has()
myMap.keys()
myMap.set()
myMap.values()

Example code of map:-

let array = [
    [1,'rahul'],
    [2,'shyam'],
    [3,'sumit'],
    [4,'subh'],
    [5,'kamal']
]
//array.map((arrayItem) => map.set(arrayItem[0], arrayItem[1]))

const myMap = new Map(array);
console.log(myMap)
myMap.set(12,'prabhash')
console.log(myMap.values())
console.log(myMap.get(4))

Note:- Objects and maps are similar in working. when the map was not introduced we have only the choice to work with the object itself. the map has some more methods as compared to objects.