0

I would like to iterate through the key of an unordered dictionary in Javascript. I don't even know if it does exist or not.

At the moment I am having the following code :

var l = [5,3,2];
var unorderedDict = {};
for (var i=0; i<l.length; i++) {
    unorderedDict[l[i]] = 'foo';
}

My dictionary will then be like : {2:'foo', 3:'foo', 5:'foo'} or in my case, I would like to keep the ordering of the initial list (so : {5:'foo', 3:'foo', 2:'foo'})

How can I achieve this ?

Scipion
  • 11,449
  • 19
  • 74
  • 139

1 Answers1

2

You cannot maintain order in object. If you want to maintain order use array:

var l = [5, 3, 2];
var val = ['foo', 'bar', 'baz'];
var unorderedDict = [];
//                  ^^
for (var i = 0; i < l.length; i++) {
  unorderedDict[l[i]] = val[i];
}

// Iterate over array:
for (var i = 0; i < unorderedDict.length; i++) {
  if (unorderedDict[i]) {
    console.log(unorderedDict[i]);
  }
}

EDIT

If you want the order to be the same as shown in l:

// Iterate over array:
for (var i=0; i<l.length; i++) {
    console.log(unorderedDict[l[i]]);
}
Tushar
  • 85,780
  • 21
  • 159
  • 179