Search code examples
javascriptarrayssortingdateobject

Sorting array of objects by ISO date


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:

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)