Home

How to sort object keys based on values?

You definitely know that objects in JavaScript are made up of keys and values. The order of the keys will be usually in the order of assignment. For example, consider the following code:

var list = {};

list.c = 35;
list.a = 12;
list.b = 1543;

Now if you log the list you will get the following

console.log(list);
// ▶ {c: 35, a: 12, b: 1543}

So you can notice that the object have three properties a,b and c in the order c,a and b. Because this is the order in which we have added them to the list object.

Now if you want to sort them based on values(ascending), you can do the following:

var sorted = Object.fromEntries(
  Object.entries(list).sort((a, b) => a[1] - b[1]),
);

console.log(sorted);
// ▶ {a: 12, c: 35, b: 1543}

Now if you want to sort them based on property names(alphabetically), you can do the following:

var sorted = Object.fromEntries(
  Object.entries(list).sort(function(a, b) {
    if (a[0] < b[0]) return -1;
    if (a[0] > b[0]) return 1;
    return 0;
  }),
);

console.log(sorted);
// ▶ {a: 12, b: 1543, c: 35}


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments