mihaifm / linq

linq.js - LINQ for JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Help: OrderByDescending chain with dates not triggereing second orderBy function (but ok if type is number)

jafin opened this issue · comments

I'm unsure why the following code does not work, the second thenByDescending fn never fires. Yet isolated each works fine. Or if the sort object values are numbers not dates it also runs as expected.

import Enumerable from "linq";

const data = [
  { startDate: new Date(2022, 1, 2), id: 3 },
  { startDate: new Date(2022, 1, 1), id: 1 },
  { startDate: new Date(2022, 1, 2), id: 5 },
  { startDate: new Date(2022, 1, 2), id: 4 },
  { startDate: new Date(2022, 1, 1), id: 2 },
];

const data2 = Enumerable.from(data)
  .orderByDescending(
    (x) => x,
    (x, y) => {
      return x.startDate > y.startDate ? 1 : x.startDate == y.startDate ? 0 : -1
      },
  )
  .thenByDescending(
    (x) => x,
    (x, y) => {
      return x.id > y.id ? 1 : x.id === y.id ? 0 : -1;
    },
  )
  .toArray();

console.log(data2);
console.log(data2[0].id === 5);

The dates are sorted yet the id is not. I'm at a loss as to why. Expect id 5 to be index 0.

[ { startDate: Wed Feb 02 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time),    id: 3 },
  { startDate: Wed Feb 02 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time),    id: 5 },
  { startDate: Wed Feb 02 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time),    id: 4 },
  { startDate: Tue Feb 01 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time),    id: 1 },
  { startDate: Tue Feb 01 2022 00:00:00 GMT+1000 (Australian Eastern Standard Time),    id: 2 } ]

If you get the Date as a number I believe that will fix the issue.
So use x.startDate.getTime() to do comparisons.

Extra value. the main problem is that the "==" comparison of startDate will always fail when you are comparing 2 different instances of a date with possibly the sam value.

Either use a.startDate - y.startDate or use getTime()

Thanks @rluiten, comparing by reference broke me and I didn't notice it.. 🙉