0
var a = ['a1', 'b2', 'd4', 'c3'];
var dict = {};

for(var i=0; i<a.length; ++i) {
dict[(a[i].match(/\d+/)[0])] = a[i];
}
console.log(dict);

for(var i=0; i<a.length; ++i) {
dict[a[i]] = a[i].match(/\d+/)[0];
}
console.log(dict);

In the first case, where keys are numbers, we have output with dictionary keys sorted.

But in second case, where keys are not numbers, we have output with a dictionary keys in the order they were added!

Is this some hidden feature, I mean is it reliable every time?

Viki
  • 421
  • 1
  • 4
  • 12
  • 2
    Arrays retain their order, objects do not (dictionary is not a JS term) – Sterling Archer Sep 12 '16 at 14:05
  • While not explicitly specified, browsers _usually_ return object keys in insertion order. However, by no means should you rely on that always being the case as there is no requirement for them to do so. – VLAZ Sep 12 '16 at 14:11
  • In both the cases, i was asking about dictionary and not array. – Viki Sep 12 '16 at 14:16
  • @Viki and both comments do address that. – VLAZ Sep 12 '16 at 14:19
  • The ones you are pointing is the second case where the objects need not be displayed in the same order. Ok! But in the first case the numbers are neatly sorted out! I've tested it with many samples and it worked! – Viki Sep 12 '16 at 14:23
  • `is it reliable every time?` - No, it is not. It is not specified in what order keys should be returned by the spec, so there is simply no guarantee the browser will do the same thing you expect it too. – somethinghere Sep 12 '16 at 14:25

1 Answers1

0

In your example a is an array and dict is simply an object.

The order of the item of an array is preserved.

There is no specification about the order of the object attributes but the order is often the one in which they were defined...if the structure is kept unchanged. There is no guarantee about the order thus.

C.Champagne
  • 5,381
  • 2
  • 23
  • 35