Home > Back-end >  Sort an array of object with key in JavaScript
Sort an array of object with key in JavaScript

Time:04-18

I am trying to sort the array of an objects with key which is date which looks like this

myArray = [{
  '2022-03-31': '32.2'
}, {
  '2022-04-01': '32.23'
}, {
  '2022-04-02': '32.9'
}, {
  '2022-03-30': '32.253'
}, {
  '2022-04-03': '32.253'
},{
  '2022-03-18': '32.253'
}]

But I want to have like this

myArray = [{
  '2022-03-18': '32.253'
}{
  '2022-03-30': '32.253'
}, {
  '2022-03-31': '32.2'
}, {
  '2022-04-01': '32.23'
}, {
  '2022-04-02': '32.9'
},{
  '2022-04-03': '32.253'
}],

I tried diff num of sols, which already there on stackoverflow, but none of them match to my case.

CodePudding user response:

Just this will work.

myArray.sort((a,b) => Object.entries(a)[0] < Object.entries(b)[0] ? -1 : 1);

Running example below:

const myArray = [
  { '2022-03-31': '32.2'   }, 
  { '2022-04-01': '32.23'  }, 
  { '2022-04-02': '32.9'   }, 
  { '2022-03-30': '32.253' }, 
  { '2022-04-03': '32.253' },
  { '2022-03-18': '32.253' },
  { '2021-06-31': '32.37' }
];

myArray.sort((a,b) => Object.entries(a)[0] < Object.entries(b)[0] ? -1 : 1);

console.log(myArray);

You can also use Object.keys instead of Object.entries like:

Object.keys(a)[0]
  • Related