0

I created a dictionary (it's just an object) in typescript using an existing array. The keys got sorted automatically. When I use an array of strings instead of numbers the sorting doesn't work. I suppose must be something related to index when using numbers as keys.

enter image description here

let dict: {[key: string]: number} = {};
const arr = [123, 333, 10, 4];

for (let el of arr) {
    dict[el] = 1;
}
console.log(dict);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
davila795
  • 1
  • 1
  • 1
    It's implementation dependent. Chrome, for instance, does sort the keys when they are numbers. – Déjà vu Sep 14 '21 at 05:06
  • 2
    @Breakingnotsobad it's "implementation dependent" only if the environment does not fully support ES6. Ever since that spec, there are rules about how keys should be iterated. Non-negative integer keys go first in ascending order, then the rest of the string keys in insertion order, finally symbol keys in insertion order. That's how they should be iterated in most cases. However, I wouldn't rely on this order as it can very easily be disturbed. Also, consoles are free to display objects as they wish, so logging one does not necessarily mean the keys are in that order. – VLAZ Sep 14 '21 at 05:18

0 Answers0