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

Why sort is not working in this array of objects?

I have this array of objects:

let a =
[{
  fecha: '2022-10-28',
  txt: 'some text',
},{
  fecha: '2022-10-26',
  txt: 'some text',
},{
  fecha: '2022-10-27',
  txt: 'some text',
}]

If I try this, it returns the array untouched:

a.sort((c,d) => c.fecha > d.fecha)

Even though, this test throws a boolean:

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

a[0].fecha > a[1].fecha // true

I don’t understand.

>Solution :

Sort functions (see the manual) should return a number which is negative, positive or 0 dependent on whether the first value is less than, greater than, or equal to the second.

Sort operates in place so there is no need to assign the output.

Since your dates are in ISO format, you can safely sort them as strings with localeCompare:

let a = [{
  fecha: '2022-10-28',
  txt: 'some text',
}, {
  fecha: '2022-10-26',
  txt: 'some text',
}, {
  fecha: '2022-10-27',
  txt: 'some text',
}]

a.sort((a, b) => a.fecha.localeCompare(b.fecha))

console.log(a)
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