JavaScript Map and Set

What exactly is a Map?

A JavaScript Map is a collection of unique keys and values. Any primitive or object can be used as both keys and values.

We use the following syntax to create a new Map:

let map = new Map([iterable]);
Example :
const scores =   new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);

console.log(scores.size); //Output Will be 5

In this example, we are using the set() method to add a key and value to the Map.

How to use map

   * Iterate through maps

There are three methods we can consider taking:

  1.     map.keys() : for keys it returns an iterable
  2.     map.entries() : returns an iterable with the elements [key, value]
  3.     map.values() : returns a values iterable

map.entries() method, which returns an iterable, provides us to iterate over the collection of keys and values, providing us to use the expanded for loop with important and necessary.

For each key-value pair, we extract the name and score as follows:

'use strict';

const scores =  new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);
scores.set('Jake', 14);
                                                              
for(const [name, score] of scores.entries()) {
  console.log(`${name} : ${score}`);
}

//output
Sara : 12
Bob : 11
Jill : 15
Bruce : 14
Jake : 14
*We can also use the  forEach method, which is an internal iterator.
const scores = new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);

scores.set('Jake', 14);
scores.forEach((score, name) => console.log(`${name} : ${score}`));

The value for a key that appears as the second parameter is carried to the function as the first parameter. To iterate over only the values, use the same forEach() method:

const scores = new Map([['Sara', 12], ['Bob', 11], ['Jill', 15], ['Bruce', 14]]);

scores.set('Jake', 14);
scores.forEach(score => console.log(score));

If you only get one parameter, it will be the value, and if you get two, it will be the value and key for each key-value pair.

 *Initialize a map with an iterable object
let userRoles = new Map([
    [sarah, 'admin'],
    [bob, 'editor'],
    [jill, 'subscriber']
]);
* Get an element from a map using a key
userRoles.get(sarah); // admin
*If you pass a key that does not exist in that map, it will return undefined.
let foo = {name: 'Foo'};
userRoles.get(foo);       //undefined
* The size property returns the number of elements in the map.
userRoles.size;        // output will be 3
* Using spread operator, convert map keys or values to arrays.
var keys = [...userRoles.keys()];
console.log(keys);

What is Set?

When the Array class of JavaScript can interact with ordered collections of data but not with unordered collections or when the collection’s values are unique, Set is used.

Duplicates are not allowed in sets. We can either create an empty set or create a set with the contents of an iterable.

const names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);
console.log(names.size);  //It will return 4

Because of duplication in the previous example One of the values is missing from the set.

We can add new elements to an existing set, as seen below:

names.add('Matt');

The add() method returns the current Set, which is useful for chain operations like more add() calls or other Set methods:

names.add('Kate')
     .add('Kara');

How do you use a set?

Sets have the following built-in functions: has(), clear(), keys(), and entries ()

Example :

const names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']); //Create 

names.add('Mike'); //Add into set

//Add multiple values into set
names.add('Kate')
     .add('Kara');

console.log(names.has('Brad')); //false                                        
console.log(names.entries()); //[Set Iterator] { 'Jack', 'Jill', 'Jake', 'Sara', 'Mike', 'Kate', 'Kara' }
console.log(names.keys()); //[Set Iterator] { 'Jack', 'Jill', 'Jake', 'Sara', 'Mike', 'Kate', 'Kara' }
console.log(names.values()); //[Set Iterator] { 'Jack', 'Jill', 'Jake', 'Sara', 'Mike', 'Kate', 'Kara' }

for(const name of names) {
  console.log(name); 
}
//output 
Jack
Jill
Jake
Sara
Mike
Kate
Kara

*filter/map with sets

const names = new Set(['Jack', 'Jill', 'Jake', 'Jack', 'Sara']);

names.add('Mike');

names.add('Kate')
     .add('Kara');

[...names].filter(name => name.startsWith('J'))
          .map(name => name.toUpperCase())
          .forEach(name => console.log(name));


* The size property is used to determine the size of a Set.

let size = chars.size;      //3

* Using the delete() method, you can remove an element from a set.

chars.delete('f'); 
console.log(chars);           // Set {"a", "b", "c", "d", "e"}

* Use the clear() method to remove all elements of a set.

 chars.clear();
 console.log(chars);    // Set{}

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories