Set and Map
Set
Set is an object used to store unique values of any type(primitive or object).
Set() = creates a new set object. It is a set constructor.
examples:
// set are object used to store unique elements
let myArray = [1,2,2,3,4] // repetition not allowed set used to store unique values
let newSet = new Set([...myArray]);
console.log(newSet);
newSet.add(7)
console.log(newSet);
console.log(newSet.has(7));
newSet.delete(3);
newSet.size;
console.log(newSet);
newSet.add({a:1, b:2});
for(const item of newSet.keys()) {
console.log(item);
}
let str = 'setmethod'
let sett = new Set([...str]);
console.log(sett);
Map
The map is an object used to store key-value pairs and remembers the original insertion order of the keys.
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// map object and remembers the original insertion order of the keys
// map any format of key and value take
console.log('MAP');
const map2 = new Map();
map2.set(0,"zero")
map2.set(1,"one");
console.log(map2);
for(const[key,value] of map2) {
console.log(`${key} = ${value}`);
}
for(const key of map2.keys()) {
console.log(key);
}
for(const value of map2.values()) {
console.log(value);
}
for(const [key,value] of map2.entries()) {
console.log(`${key} = ${value}`);
}
map2.set(3,"three")
console.log(map2.get(3));
let map = new Map()
console.log(map.size);
let arr = [[1, "Mithun"],
[2, "Alka"], [3, "Prabir"], [4, "Shivam"], [5, "Vinay"]];
const a = arr.map((arrayItem)=> map.set(arrayItem[0],arrayItem[1]));
console.log(a);