Home > Software design >  sort a javascript object by key : '10' is before '05'
sort a javascript object by key : '10' is before '05'

Time:05-18

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" }

CodePudding user response:

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

CodePudding user response:

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);
}

  • Related