Skip to main content

Command Palette

Search for a command to run...

Js - Maps and set

Updated
3 min read
Js - Maps and set

Set

It's just like arrays but contains only unique values (you can store anything numbers, strings, arrays, objects,.. as items inside it)

let arr = [1,2,2,3,3,3]

let s = new Set(arr)

console.log(s)
console.log(s.size)

s.add(7)
s.add(2) // silent fail
console.log(s)

s.delete(1)

console.log(s)
console.log(s.has(2), s.has(1))

s.clear()

console.log(s)

Output

Set(3) { 1, 2, 3 }
3
Set(4) { 1, 2, 3, 7 }
Set(3) { 2, 3, 7 }
true false
Set(0) {}

You can also perform Math operations like union , intrsection, etc

Iterating

let arr = [1,2,2,3,3,3]

let s = new Set(arr)

for(let i of s){
    console.log(i)
}

// or

s.forEach((item)=>(console.log(item)))

Output

1
2
3

MDN docs for set

Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values ) may be used as either a key or a value.

Unlike object where a key can only be string or symbol a map's key can be anything.

A key in the Map may only occur once;

const map = new Map();

map.set("a", 1);
map.set("b", 2);
map.set("c", 3);

console.log(map.get("a"));
// Expected output: 1

map.set("a", 97);

console.log(map.get("a"));
// Expected output: 97

console.log(map.size);
// Expected output: 3

map.delete("b");

console.log(map.size);
// Expected output: 2

iterating

const map = new Map([["a", 1], ["b", 2], ["c", 3]]); 
// another way to set key value pairs is using array of arrays

for (const [key,value] of map) {
    console.log(`\({key} : \){value}`)
}

output

a : 1
b : 2
c : 3

using forEach()

map.forEach((key,value)=>(console.log(key, value)))

/*

1 a
2 b
3 c

*/

Making a Hash map

given a array of numbers print by console logging the map with numbers being the key and frequencies being the value derived from the given array.

[ 1, 4, 2, 2, 2, 2, 2, 42, 2, 4, 0, 2, 2 , 4, 1]

const arr = [ 1, 4, 2, 2, 2, 2, 2, 42, 2, 4, 0, 2, 2 , 4, 1]
const hashMap = new Map()

arr.forEach((num)=>{
    hashMap.has(num) ? hashMap.set(num, hashMap.get(num)+1) : hashMap.set(num, 1)
})

console.log(hashMap)
// Map(5) { 1 => 2, 4 => 3, 2 => 8, 42 => 1, 0 => 1 }

hashMap.get(num) will only return the copy of the value hence incrementing it will not change the original value.