How are elements ordered in a Map in JavaScript ?
In JavaScript, a new object called Map was introduced in the ES6 version. A map is a collection of elements where each element is stored in a key, value pair. Map objects can store both objects as well as primitive data types. The elements of a map are iterable. Elements are always iterated in the insertion order.
The elements in a map are ordered which means that the elements can be iterated in the order they are inserted.
Syntax:
new Map([it])
Example 1: In this example, we will create a new map object and iterate over it to check how the elements are ordered.
Javascript
var sample = new Map(); sample.set( "name" , "Rahul" ); sample.set( "age" , 20); sample.set( "Country" , "India" ); for ( var [key, value] of sample){ console.log(`Key = ${key}, Value=${value}`) } |
Output:
Key = name, Value=Rahul Key = age, Value=20 Key = Country, Value=India
Example 2: In this example, we will save the keys and values of the map in two different arrays
Javascript
var sample = new Map(); sample.set( "name" , "Rahul" ); sample.set( "age" , 20); sample.set( "Country" , "India" ); var keys = sample.keys(); var val = sample.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']
Explanation: We can see that the elements maintain the order they are entered in the map so the insertion in new arrays follows the same order as that of the map
Please Login to comment...