简体   繁体   English

按多个字段排序 typescript

[英]Sort by multiple field typescript

I'm trying to sort on multiple fields but I can't do it我正在尝试对多个字段进行排序,但我做不到

My array:我的数组:

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
}
]

I would like to sort by decreasing date and by decreasing rank to get the following result:我想按日期递减和排名递减排序以获得以下结果:

 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
    },
]

On my project, for the dates, Luxon is used.在我的项目中,日期使用的是 Luxon。 I did the following treatment but I don't get the right result...:我做了以下治疗,但我没有得到正确的结果......:

component.ts:组件.ts:

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

service.ts:服务.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;

  }

Can you help me please?你能帮我吗? :) :)

Thank you谢谢

Fixed your code a bit, and created 2 sorting functions.稍微修正了您的代码,并创建了 2 个排序函数。 First by date and then if the date is the same, sort by rank.首先按日期,然后如果日期相同,则按排名排序。

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 play link: https://tsplay.dev/WzLKQN TS播放链接: https://tsplay.dev/WzLKQN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM