HomeSoftware DevelopmentHow are parts ordered in a Map in JavaScript ?

How are parts ordered in a Map in JavaScript ?


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

In JavaScript, a brand new object referred to as Map was launched within the ES6 model. A map is a set of parts the place every aspect is saved in a key, worth pair. Map objects can retailer each objects in addition to primitive information sorts. The weather of a map are iterable. Components are at all times iterated within the insertion order.

The weather in a map are ordered which signifies that the weather might 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("title", "Rahul");

pattern.set("age", 20);

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

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

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

}

Output:

Key = title, 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 completely different arrays 

Javascript

var pattern = new Map();

pattern.set("title", "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 are able to see that the weather preserve the order they’re entered within the map so so the insertion in new arrays follows the identical order as that of the map  

RELATED ARTICLES

Most Popular

Recent Comments