Set-Map in JavaScript

The set is a collection of unique values in javascript. That takes values individually or in the form of an array. The data type of Set is an object.
Example :const set1 = new Set(); // set constructionset1.add(1); // adding an element in setset1.add(2);set1.add(3);const obj = { name : 'Harshit', SRN : 'S21PA12' };set1.add(obj)set1.has(2);//trueset1.delete(3); // remove 3 from setconsole.log(set1)// Set(3){1,2,{...}}
Features of Set :
The set contains unique values.
It maintains insertion order.
the Set has some methods that manage the insertion, deletion, updation and removing elements.
Some everyday use of the Set in JavaScript :
To remove duplicate elements in an array.
Example :
const arr = [1,2,2,5,3,6,4,5,7,5];
const newArr = [...new Set(arr)];console.log(newArr);// [1,2,5,3,6,4,7]To check if an element is in a collection.
Example :
const set1 = new Set([1,2,3,4]);console.log(set.has(2));//trueconsole.log(set.has(23));//falseFinding the union, intersection, or difference of two sets.
Example :
const set1 = new Set([1, 2, 3]);const set2 = new Set([2, 3, 4]);const union = new Set([...set1, ...set2]);console.log(union); // Set {1, 2, 3, 4}const intersection = new Set([...set1].filter(x => set2.has(x)));console.log(intersection); // Set {2, 3}const difference = new Set([...set1].filter(x => !set2.has(x)));console.log(difference); // Set {1}
The map is a collection of key-value pairs. A key should be unique or may only occur once. It is iterable and maintains insertion order, the key-value pair inserted by the set method.
Example :const myMap = new Map();// map construction//setting the valuesmyMap.set('Name','Harshit');myMap.set('SRN','S2143D12');myMap.set('Sem',4);console.log(myMap.size);// 3//getting the valueconsole.log(myMap.get(Name));// Harshit
Methods of Map
set: It is used to set key-value in to map.
Example :
const myMap = new Map();
myMap.set('a',1);// set key-value
myMap.set('b',2);get: It is used to get value according to a given key.
Example :
console.log(myMap.get('a'))// 1has: It returns a boolean value according to the key-value present or not.
Example :
console.log(myMap.has(1));// true
console.log(myMap.has('harshit'));// falsekeys: It returns all keys that are present in the map.
Example :
console.log(myMap.keys()); // {a,b}values: It returns all values that are present in the map.
Example :
console.log(myMap.values()); // {1,2}delete: It returns a boolean when the successful key-value is deleted.
Example :
const map1 = new Map();
map1.set('bar', 'foo');console.log(map1.delete('bar'));
// Expected result: true
// True indicates successful removalconsole.log(map1.has('bar')); // Expected result: falseclear: It is used to remove all key-value from the map.
Example :
const map1 = new Map();map1.set('bar', 'baz'); map1.set(1, 'foo');console.log(map1.size); // Expected output: 2map1.clear();console.log(map1.size); // Expected output: 0