Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort an array of object with key in JavaScript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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' }
];

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading