0

I'm using the following function to sort an object by keys.

The problem is when I have to sort '05' and '10', the '10' is sorted before the '05'

function sortObj(obj) {
  return Object.keys(obj).sort().reduce(function(result, key) {
    result[key] = obj[key];
    return result;
  }, {});
}

let list = {
  '10': "Ann",
  '05': 75
};
let arr = sortObj(list);
console.log(arr);

Object { "10": 75, "05": "Ann" }

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Paul
  • 1,290
  • 6
  • 24
  • 46
  • the sorting is correct with `list = { '10_':"Ann", '05_':75 };` – Paul May 17 '22 at 22:33
  • 1
    Why do you want to sort an object? It makes absolutley no sense. It makes sense to sort an array, but not an object. Also your result `arr` is not an array, its still an object – bill.gates May 17 '22 at 22:40

2 Answers2

0

Javascript objects are not ordered by insertion order. To demonstrate, change .sort() to .reverse()

Does JavaScript guarantee object property order?

Seems like you can use a map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared

ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18
0

Ordering an object makes little sense, because objects don't concern itself about the order it is as you access it's values by a key.

Though you can store your data in a Map which has a key-value structure that honors it's order of insertion.

function sortObj(obj) {
  return new Map(
    Object.entries(obj).sort(([a], [b]) => {
      return a - b;
    })
  );
}

let list = {
  '11': 'Beth',
  '10': "Ann",
  '05': 75,
  '07': true
};

let map = sortObj(list);
for (const [key, value] of map) {
  console.log(key, value);
}
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32