0

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.

Bruja
  • 368
  • 2
  • 10

2 Answers2

4

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)
Nick
  • 138,499
  • 22
  • 57
  • 95
1

Hope this is what you need, just add Date.parse() it becomes (timestamp)

 let a = [
        {
          fecha: "2022-10-27",
          txt: "some text"
        },
        {
          fecha: "2022-10-28",
          txt: "some text"
        },
        {
          fecha: "2022-10-26",
          txt: "some text"
        }
      ];
    
      a.sort((a, b) => Date.parse(b.fecha) - Date.parse(a.fecha));
    
      console.log(a);
Jackson Quintero
  • 178
  • 1
  • 1
  • 8
  • 1
    Yes, `Date.parse` is a decent approach, making use of the `-` operator’s numeric type coercion. Strictly speaking, parsing a date from a string should be avoided (see the [documentation](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#date_string)). ISO dates are probably the only acceptable string format for this purpose. Fortunately, [ISO dates](//en.wikipedia.org/wiki/ISO_8601#General_principles) have the useful property that they can also simply be sorted lexicographically. – Sebastian Simon Oct 29 '22 at 01:18
  • @SebastianSimon— *Date.parse* returns a number (which might be *NaN*), so the minus operator doesn't do any coercion in this case. :-) – RobG Oct 29 '22 at 08:12
  • @RobG Huh, it really does return a number. Well, I never use `Date.parse`, I always use `new Date` directly. I think I thought that these were the same because they _accept_ the same input. I never really noticed that they _return_ different things. – Sebastian Simon Oct 29 '22 at 10:22