JavaScript: Sort Object of Objects

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an Object of Objects like this −

const obj = {
   "CAB": {
      name: 'CBSSP',
      position: 2
   },
   "NSG": {
      name: 'NNSSP',
      position: 3
   },
   "EQU": {
      name: 'SSP',
      position: 1
   }
};

We are required to write a JavaScript function that takes in one such array and sorts the sub-objects on the basis of the 'position' property of sub-objects (either in increasing or decreasing order).

Example

The code for this will be −

const obj = {
   "CAB": {
      name: 'CBSSP',
      position: 2
   },
   "NSG": {
      name: 'NNSSP',
      position: 3
   },
   "EQU": {
      name: 'SSP',
      position: 1
   }
};
const sortByPosition = obj => {
   const order = [], res = {};
   Object.keys(obj).forEach(key => {
      return order[obj[key]['position'] - 1] = key;
   });
   order.forEach(key => {
      res[key] = obj[key];
   });
   return res;
}
console.log(sortByPosition(obj));

Output

And the output in the console will be −

{
   EQU: { name: 'SSP', position: 1 },
   CAB: { name: 'CBSSP', position: 2 },
   NSG: { name: 'NNSSP', position: 3 }
}
raja
Published on 21-Nov-2020 14:27:39
Advertisements