Map and Set Method

Map and Set

Developers use Objects to store key/value pairs and Arrays to store indexed lists. However, to give developers more flexibility, the ECMAScript 2015 specification introduced two new types of iterable objects: Maps, which are ordered collections of key/value pairs, and Sets, which are collections of unique values.

In this article, will see the Map and Set objects, their properties and methods with examples of some practical uses and how map is difference from an object.

Map

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows any type of key. Although we can access object as a key in map. Where in object we can’t access object as key in object.

A Map maintain the order of its entries. Maps have elements of both Objects (a unique key/value pair collection) and Arrays (an ordered collection), are more similar to Objects . This is because, the size and order of entries is preserved like an Array, the entries themselves are key/value pairs like Objects.`

Maps can be initialized with the new Map() syntax:

const map = new Map()

This gives us an empty Map:

Map(0) {}

Note:  1.A Map holds key-value pairs where the keys can be any datatype.

2.A Map remembers the original insertion order of the keys

3.  A Map has a property that represents the size of the map.

Methods and properties:

  • new map([iterable])- creates the map, with optional iterable (e.g. array) of [key,value] pairs for initialization.
  • map.set(key,value)-  stores the value by the key, returns the map itself.
  • map.get(key)-  returns the value by the key, undefined if key doesn’t exist in map.
  • map.has(key)- returns true if the key exists, false otherwise.
  • map.delete(key)-  removes the element by the key, returns true if key existed at the moment of the call, otherwise false.
  • map.clear()-  removes everything from the map.
  • map.size()- returns the current element count.

Examples of map properties and methods:

1) new Map( )

//create a Map

let  map = new Map([

[‘banana’,100],

[‘apple’,300],

[‘mango’,400]

]);

console.log(map)

In above example map initialized with the new Map() syntax and array of object passed as a data into new Map(). We passed three keys here a number, a string , an (key,value) pair.

Map uses the => syntax to signify key/value pair as key => value

2) map.set (key,value )

We can add values to a map with the set( ) method. The first argument will be key , and the second argument will be the value.

//set map value

map.set(‘100’, ‘string1’);

map.set( 200 , ‘number1’);

map.set(true, ‘boolean1’);

console.log(map)

Here we added (key,value) pair data as key into exciting map by map.set( ) method . three key/value pair we added to map having a string key, a numeric key, an a Boolean key.

Output:

{Jhon=> undefined, ‘Mello’ => undefined, ‘age’ => 20, ‘100’ => ‘string1’, 200 => ‘number1’, …}

This looks similer to a regular object with string-based keys,but we can use any data type as a key with map

3) map.get( )

Get method returns the value by key

//get value by the key

console.log(map.get(200))

console.log(map.get(‘100’))

console.log(map.get(2))

In this example we returing the value for each key

Output:   number1

string1

undefind

Here, map.get( ) method returns the value for number and string key.for Boolean key it’s returns undefind value

4) map.size

This the main property of map , which returns the number of items in map. (returns current element count).

//returns element count

console.log(map.size)

here we getting size of our exiciting map using map.size

Output: 6

It retruns the 6 number of count.means size of map is 6.

5)   map.has()

Map.has() method checks the existence of an item in Map by key. And returns the boolean value(true/false)

//returns boolean value

console.log(map.has(1))

console.log(map.has(2))

We used key of  item to check  where it is presence in map or not.

 Output:  true

false

The result is true for a 1 number ,as it’s present in exciting map as (1, ‘number’) key value pair.and the another result is false casue value for 2 is undefind.

6) map.delete()

It simply remove an key/value pair from a Map by key. Use the delete() method to remove an item from a Map by key. The method will return a Boolean—true if an item existed and was deleted, and false if it did not match any item.

//removes the element from map

map.delete(‘age’)

console.log(map.delete(‘age’))

console.log(map.size)

In above example we deleted the ‘key1’ item from the map

 Output:  true

5

For deleting the ‘key1’ item it returns the true. The original size of map is 6 after deleting the ‘key1’ item the size of map become 5.

7) map.clear()

It clear the all of values from the map ,and returns N/A.the size of map is 0 .

//removes everything from map

map.clear(map)

console.log(map)

Output:  Map(0)

0

Map Chaining

Every map.set call returns the map itself, so we can “chain” the calls:

map.set(‘1’, ‘str1’);

.set(1, ‘num1’);

.set(true, ‘bool1’);

 

Iteration over maps

For looping over a map, there are 3 methods:

  • map.keys()– returns an iterable for keys,
  • map.values() – returns an iterable for values,
  • map.entries()– returns an iterable for entries [key, value], it’s used by default in for..of.

let travelMap = new Map([

[‘thailand’, 500],

[‘europe’, 350],

[‘switherland’, 450]

]);

 

// iterate over keys (placess)

for (let places of travelMap.keys()) {

console.log(places);

}

 

// iterate over values (amounts)

for (let amount of travelMap.values()) {

console.log(amount);

}

 

// iterate over [key, value] entries

for (let entry of travelMap) {            // the same as of recipeMap.entries()

console.log(entry);

}

 

The iteration goes in the same order as the values were inserted. Map preserves this order, unlike a regular Object.

forEach method

Map has a built-in forEach method, similar to Array,for built-in iteration. However, there is a bit of a difference in what they iterate over. The callback of a Map’s forEach iterates through the value, key, and map itself, while the Array version iterates through the item, index, and array itself.

// Map

Map.prototype.forEach((value, key, map) = () => {}

// Array

Array.prototype.forEach((item, index, array) = () => {}

This is a big advantage for Maps over Objects, as Objects need to be converted with keys(), values(), or entries(), and there is not an simple way to retrieve the properties of an Object without converting it.

forrEach method in map:

// runs the function for each (key, value) pair

travelMap.forEach( (value, key, map) => {

console.log(`${key}: ${value}`);

});

 

Map from Object: (Object.entries)

If we have a plain object, and we’d like to create a Map from it, then we can use built-in method (Object.entries(Obj)) that returns an array of key/value pairs for an object exactly in that format.

let obj = {

firstName: “John”,

lastName: “swan”,

age: 30

};

Let map = new Map(Object.entries(obj));

console.log(map); // John

Here, Object.entries returns the array of key/value pairs.

 

Object from Map: (Object.entries(obj))

We’ve just seen how to create Map from a plain object with Object.entries(obj).

There’s Object.fromEntries method that does the reverse: given an array of [key, value] pairs, it creates an object from them:

 Let prices = Object.fromEntries([

[‘banana’, 1],

[‘orange’, 2],

[‘meat’, 4]

]);

console.log(prices);

console.log(prices.orange);

We can use Object.fromEntries to get a plain object from Map.

E.g. we store the data in a Map, but we need to pass it to a 3rd-party code that expects a plain object.

 let map = new Map();

map.set(‘banana’, 1);

map.set(‘orange’, 2);

map.set(‘meat’, 4);

let obj = Object.fromEntries(map.entries()); // make a plain object (*)

console.log(obj)

console.log(obj.orange);

A call to map.entries() returns an iterable of key/value pairs, exactly in the right format for Object.fromEntries.

We could also make line (*) shorter:

//We could also make line (*) shorter:

let obj = Object.fromEntries(map); // omit .entries()

That’s the same, because Object.fromEntries expects an iterable object as the argument. Not necessarily an array. And the standard iteration for map returns same key/value pairs as map.entries(). So we get a plain object with same key/values as the map.

Set

A Set is a special type collection – “set of values” (without keys), where each value may occur only once.

Set methods :

  • new Set([iterable])- creates the set, with optional iterable (e.g. array) of values for initialization.
  • add(value) – adds a value (does nothing if value exists), returns the set itself.
  • delete(value)- removes the value, returns true if value existed at the moment of the call, otherwise false.
  • has(value)- returns true if the value exists in the set, otherwise false.
  • clear()- removes everything from the set.
  • size– is the elements count.

The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason why each value appears in a Set only once.

  let set = new Set();

let john = { name: “John” };

let pete = { name: “Pete” };

let mary = { name: “Mary” };

// visits, some users come multiple times

    set.add (john);

set.add (pete);

set.add (mary);

set.add (john);

set.add(mary);

// set keeps only unique values

    console.log( set.size );

 

for (let user of set) {

console.log(user.name);

}

The alternative to Set could be an array of users, and the code to check for duplicates on every insertion using arr.find. But the performance would be much worse, because this method walks through the whole array checking every element. Set is much better optimized internally for uniqueness checks.

Iteration over Set

We can loop over a set either with for..of loop or using forEach loop:

const SetMethod = () => {

let set = new Set([“oranges”, “apples”, “bananas”]);

 

    for (let value of set)

console.log(value);

 

    // the same with forEach:

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

console.log(value);

});

The callback function passed in forEach has 3 arguments: a value, then the same value valueAgain, and then the target object. Indeed, the same value appears in the arguments twice. That’s for compatibility with Map , this may help to replace Map with Set in certain cases with ease, and vice versa.

 

Map Set
It is an interface that is responsible for mapping unique keys to the values. It is an interface that comes under the Collection interface and it is not capable of carrying duplicate elements.
It is a separate independent interface. Set is responsible for extending the collection interface.
The function of Map is to connect between key and value. The function of Set is to store unique values.
The Map can have as many null values as possible. At most Set can have one null value.
To store the data in the form of a key or value one should utilize Map. To create a collection of unique components Set should be used.