0

The Object.entries() method seem to output the keys in an ascending order:

// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]

I am not sure it this is always the case, but if it is so, is there any way of reversing the order?

cidetto
  • 43
  • 2
  • 9
  • Objects are not ordered, `entries` might output anything. Use an array if you need a specific order. – Bergi Apr 16 '18 at 20:34
  • _The Object.entries() method seem to output the keys in an ascending order_ No, the object literal is sorted like that, Object.entries() doesn't change any order – baao Apr 16 '18 at 20:34
  • 2
    it is always the case for keys who could read as 32 bit integer numbers (like indices of arrays). – Nina Scholz Apr 16 '18 at 20:44

1 Answers1

2

Sure, just reverse the array before logging it:

const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj).reverse());

But keep in mind that property names should not be relied upon to be ordered - it's not in the spec. Better to explicitly select properties in your desired order - perhaps use a sort function first.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320