How to sort an object in ascending order by the value of a key in JavaScript?


Suppose we have the following object −

const obj = {
   "sub1": 56,
   "sub2": 67,
   "sub3": 98,
   "sub4": 54,
   "sub5": 87
};

We are required to write a JavaScript function that takes in one such object. Then our function should sort the object in ascending order of the values present in the object. And then at last, we should return the object thus formed.

Example

The code for this will be −

const obj = {
   "sub1": 56,
   "sub2": 67,
   "sub3": 98,
   "sub4": 54,
   "sub5": 87
};
const sortObject = obj => {
   const sorter = (a, b) => {
      return obj[a] - obj[b];
   };
   const keys = Object.keys(obj);
   keys.sort(sorter);
   const res = {};
   keys.forEach(key => {
      res[key] = obj[key];
   });
   return res;
};
console.log(sortObject(obj));

Output

And the output in the console will be −

{ sub4: 54, sub1: 56, sub2: 67, sub5: 87, sub3: 98 }

Updated on: 20-Nov-2020

655 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements