按多字段打字稿排序

Sort by multiple field typescript

我正在尝试对多个字段进行排序,但我做不到

我的阵列:

details = [
{
  dateDebut: '2014-10-10',
  rank:1
},
{
  dateDebut: '2020-12-12',
  rank:0
},
{
  dateDebut: '2014-10-10',
  rank:0
},
{
  dateDebut: '2014-10-10',
  rank:2
},
{
  dateDebut: '2020-11-11',
  rank:1
},
{
  dateDebut: '2020-11-11',
  rank:0
}
]

我想按递减日期和递减排名进行排序以获得以下结果:

 details = [
    {
      dateDebut: '2020-12-12',
      rank:0
    },
    {
      dateDebut: '2020-11-11',
      rank:1
    },
    {
      dateDebut: '2020-11-11',
      rank:0
    },
    {
      dateDebut: '2014-10-10',
      rank:2
    },
    {
      dateDebut: '2014-10-10',
      rank:1
    },
    ,
    {
      dateDebut: '2014-10-10',
      rank:0
    },
]

在我的项目中,日期使用的是 Luxon。 我做了以下处理,但我没有得到正确的结果......:

component.ts :

details.sort((d1, d2) => this.myService.sortByRangAndDates(d1, d2, 'desc'));

service.ts :

sortByRangAndDates(d1: Details, d2: Details, order: 'asc' | 'desc'): number {
    const orderValue = order === 'desc' ? -1 : 1;

    const convert = (s: string): number => {
      return s ? new Date(s).getUTCDate() : 0;
    };


    return (convert(d1?.dateDebut) < convert(d2?.dateDebut)) || (d1.rank < d2.rank ) ? orderValue :
      (convert(d1?.dateDebut) > convert(d2?.dateDebut)) || (d1.rank > d2.rank ) ? -1 * orderValue : 0;

  }

你能帮帮我吗? :)

谢谢

稍微修正了您的代码,并创建了 2 个排序函数。首先按日期排序,如果日期相同,则按排名排序。

type Details = {
  dateDebut: string;
  rank: number;
};
const convert = (s: string): number => s ? new Date(s).getTime() : 0

const sortByDate = (d1: Details, d2: Details, order: string): number =>
  order == "asc"
    ? convert(d1.dateDebut) > convert(d2.dateDebut)
      ? 1
      : -1
    : convert(d1.dateDebut) > convert(d2.dateDebut)
    ? -1
    : 1;

const sortByRange = (d1: Details, d2: Details, order: "asc" | "desc"): number =>
  d1.dateDebut == d2.dateDebut
    ? order == "asc"
      ? d1.rank > d2.rank
        ? 1
        : -1
      : d1.rank > d2.rank
      ? -1
      : 1
    : 0;
details.sort((d1, d2) => sortByDate(d1, d2, "desc"));
details.sort((d1, d2) => sortByRange(d1, d2, "desc"));

console.log(details);

TS 播放 link: https://tsplay.dev/WzLKQN