Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the sequence in javascript Map?

i have myData map as below

 var myData =  new Object();

 myData[10427] = "Description 10427";
 myData[10504] = "Description 10504";
 myData[10419] = "Description 10419";

but now when i iterate over myData, i don't get same sequnce in chrome and IE works fine in firefox. It iterates in ascending order of key

for (var key in myData) {
  alert("key is"+key);
  }

i get the output in ascending order in alert as 10419,10427,10504

How i can make sure to iterate in same order as data as inserted in map?

like image 583
emilly Avatar asked Jul 17 '13 09:07

emilly


People also ask

Do JavaScript maps maintain order?

A Map is a collection of key/value pairs that can use any data type as a key and can maintain the order of its entries.

Does HashMap maintain insertion order in JavaScript?

Here, the original insertion order of HashMap is [01, 03, 04, 02], but the output is different [01, 02, 03, 04]. It did not maintain the original insertion order of the elements.

Does array map preserve order JS?

The underlying issue isn't because of map , which should preserve the order. Rather, user.jobs itself may be in a different order (in each test) since there isn't any explicit order by clause used. Without an explicit order by , you can't guarantee the order of the jobs even if you create them in a specific order.

How do I iterate through a map in JavaScript?

Iterate through a Map using JavaScript # Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.


1 Answers

ES6 Maps preserves the insertion order.

The set method is used for setting the key value pairs

var myData = new Map();
myData.set(10427, "Description 10427");
myData.set(10504, "Description 10504");
myData.set(10419, "Description 10419");

Map keys and values are printed using

myData.forEach((value,key) => console.log(key, value));

This will print the keys and values in the insertion order

like image 168
Mamtha Soni K Avatar answered Oct 06 '22 22:10

Mamtha Soni K