Software Development

How are components ordered in a Map in JavaScript ?

How are components ordered in a Map in JavaScript ?
Written by admin


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

In JavaScript, a brand new object known as Map was launched within the ES6 model. A map is a set of components the place every ingredient is saved in a key, worth pair. Map objects can retailer each objects in addition to primitive knowledge sorts. The weather of a map are iterable. Parts are all the time iterated within the insertion order.

The weather in a map are ordered which implies that the weather may be iterated within the order they’re inserted.

Syntax:

new Map([it])

Instance 1:  On this instance, we’ll create a brand new map object and iterate over it to test how the weather are ordered.

Javascript

var pattern = new Map();

pattern.set("identify", "Rahul");

pattern.set("age", 20);

pattern.set("Nation", "India");

for(var [key, value] of pattern){

    console.log(`Key = ${key}, Worth=${worth}`)

}

Output:

Key = identify, Worth=Rahul
Key = age, Worth=20
Key = Nation, Worth=India

 Instance 2:  On this instance, we’ll save the keys and values of the map in two totally different arrays 

Javascript

var pattern = new Map();

pattern.set("identify", "Rahul");

pattern.set("age", 20);

pattern.set("Nation", "India");

var keys = pattern.keys();

var val = pattern.values()

var arr= [];

var arr2 = [];

for (var ele of keys){

    arr.push(ele)

}

console.log(arr);

for (var ele of val){

    arr2.push(ele)

}

console.log(arr2);

Output:

(3) ['name', 'age', 'Country']
(3) ['Rahul', 20, 'India']

Clarification: We will see that the weather keep the order they’re entered within the map so so the insertion in new arrays follows the identical order as that of the map  

About the author

admin

Leave a Comment