16

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?

3
  • Use a string instead of a number. Something like myDate['10427'] = "Description 10427";. If you just use a number it gets added at that index in the array. Commented Jul 17, 2013 at 9:48
  • 1
    @putvande — Nonsense. The value you pass to square bracket notation will be stringified before use. Plain objects are always unordered. Commented Jul 17, 2013 at 9:48
  • Ow my bad... I thought the question was about an Array. Misread it. Commented Jul 17, 2013 at 10:07

2 Answers 2

64

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

Sign up to request clarification or add additional context in comments.

2 Comments

"The Map object holds key-value pairs and remembers the original insertion order of the keys." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Console.log it printed insertion order, but while iterating in HTML, it not maintaining the insertion order.
8

Objects are unordered in JS. Use an array if order matters.

var myData = [];
myData.push({ "number": 10427, description: "Description 10427" });

4 Comments

i do not want the order i want the same sequence(while iteration) as the sequnce of data insertion
If you want them in insertion order, then don't sort them.
i am not sorting them. They are getting automatically in chrome and ie but works fine in firefox
If you want them in insertion order, then store them in an array as per this answer and don't sort the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.