0

Assuming I have this code below:

const list = [22, 13, 17, 11, 0];
let obj = {};

for (let val of list) {
  obj[val] = false;
}

console.log(obj);

The result is:

{
 0:false,
 11:false,
 13:false,
 17:false,
 22:false
}

It re-arranges the original order in the list. How do I stop it from doing so?

cherieodu
  • 43
  • 3
  • 1
    Why does the order matter? – charlietfl Dec 17 '21 at 03:08
  • Fundamentally, an object is not for storing ordered data. This is the major difference between [keyed collections](//tc39.es/ecma262/#sec-keyed-collections) and [indexed collections](//tc39.es/ecma262/#sec-indexed-collections). Use an [Array](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) instead. Alternatively, use a [Map](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) instead which also guarantees insertion order. – Sebastian Simon Dec 17 '21 at 03:12

0 Answers0