Learn Js with Ut

Map and Set in js

June 20, 2020

Map 😎

Map is like an object. It store element in key,value pair form. But the main difference is that Map allows keys of any type.

Methods and properties in Map:

  • new Map() - creates the map.
  • map.set(key,value) - stores the value by the key.
  • map.has(key) - returns true if key exist otherwise return false.
  • map.get(key) - return the value on which the key points,undefined if key doesn’t exist in map.
  • map.delete(key) - removes the value by the key.
  • map.clear() - removes everything from the map.
  • map.size - returns the current elements count.

Let’s experiment something:

let map = new Map(); // Intialize an map

map.set('1','key is string'); //a string key
map.set(1,'key is numeric'); //a numeric key
map.set(true,"key is boolean"); // a boolean key

// normal object convert the key into string type
//but map keeps the type
// It didn't convert the key into string type

console.log(map.get(1)); // 'key is numeric'
console.log(map.get('1')); // 'ket is string'
console.log(map.size); //3

Map can also use objects as keys

For example:

let user = {name:'utkarsh'};

let map = new Map();
// Here we use object as a key to store values
map.set(user,434);

console.log(map.get(user)); // 434

Using object as a key is one of the most important Map features. Object {} doesn’t support keys as an object {}.

Let’s see:

let user = {name:"utkarsh"};
let obj = {} // a simple object
obj[user] = 123; //trying to use object as a key in obj
console.log(obj); //{[object Object]: 123}
console.log(obj["[object Object]"]); // 123

Here obj is an object,it converts all the keys in string, such as user object. So on consoling obj it returns {[object Object]: 123}

Iteration over Map

There are 3 methods for looping a map:

  • map.keys() - returns all the keys of an map.
  • map.values() - returns all the values of an map.
  • map.enteries() - returns an all [key,value].

For example:

// Let a map with customerName or there with roomno
let customers = new Map([
  ['John',300],
  ['Jack',200],
  ['saun',190]
]);
// iterate over the keys
for(let names of customers.keys()){
  console.log(names); // 'John', 'Jack','saun'
}
// iterate over the values
for(let rooms of customers.values()){
  console.log(rooms); // 300, 200, 190
}
// iterate over the enteries
for(let entry of customers.entries()){
  console.log(entry);
// [John,300]
// [Jack, 200]
// [saun, 190]
}
// We can also write customers in place of customers.entries()
for(let entry of customers){
  console.log(entry);
// [John,300]
// [Jack, 200]
// [saun, 190]
}

Map has built-in forEach method similiar to Array

For example:

let customers = new Map([
  ['John',300],
  ['Jack',200],
  ['saun',190]
]);
//forEach on customers

customers.forEach((value,key,map)=>{
console.log(key,value);
 // John,300
// Jack, 200
// saun, 190
console.log(map);
//{"John" => 300, "Jack" => 200, "saun" => 190} //so on
});

If we want to create Map by passing a simple object {}. Then we can use built-in method Object.entries(obj) that returns an array of key/value pairs for an object.

For Example:

let obj = {
  name:"utkarsh",
  age:24
};

let map = new Map(Object.entries(obj));
console.log(map.get('name')); // utkarsh

Here Object.entries(obj) returns [["name","utkarsh"],["age",24]]that’s Map needs.

Set 🔥

A Set is a “set of values” (without keys), where each value may occur only once. In Set duplicate values are not allowed.

Method and properties in Set

  • new Set()- creates the set.
  • set.add(value) - adds a value, returns the set itself.
  • set.delete(value) - removes the value,returns true. If value existed at the moment of the call,otherwise returns false.
  • set.has(value) - returns true if the value exists in the set, otherwise false.
  • set.clear() - removes everything from the set.
  • set.size - is the element count.

Repeated call of set.add(value) with the same value don’t do anything. That’s why each value in set are unique.

For Example:

let set = new Set();

let hollyMovies = {name:"Avenger"};
let bollyMovies = {name:"Rockstar"};
let favMovies = {name:"Batman"};

set.add(hollyMovies)
   .add(bollyMovies)
   .add(favMovies)
   .add(bollyMovies)
   .add(hollyMovies);
   // set keeps only unique values
console.log(set.size); // 3
// Iterating set
for(let movie of set){
  console.log(movie);
  // Avenger
  // Rockstar
  // Batman
}

forEach in set

For Example:

let set = new Set(["Avenger","Mission Impossible","Batman"]);

set.forEach((value,valueAgain,set)=>{

console.log(value);
//Avenger
//Mission Impossible and so on
});

Above forEach function has 3 arguments value - value of set and valueAgain is the same value of an set. Here the same value appears in the arguments twice.

Iterators in set

Set supported same methods for iterators as Map

  • set.keys() - returns an iterable object for values.
  • set.values() - same as set.keys().
  • set.entries() - returns an iterable object for enteries [value,value].

This is all about Map and Set hope you 👍



Please subscribe our news letter

If you like what you just read. Please subscribe to our newsletter. So new content will be delivered to your inbox :)

Hii this is Utkarsh Srivastava. I live in India. I
Coding, Learning New Tech, and Playing PC Games. You can find me on
© 2020, Built with