I am facing an issue with sorting on multiple fields in my array
Here is the 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 descending date and rank to achieve 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
},
]
In my project, Luxon is used for handling dates. I have tried a certain treatment but haven't been successful. Can you please assist me?
This is how I am trying to implement it:
details.sort((d1, d2) => this.myService.sortByRangAndDates(d1, d2, 'desc'));
Here is the snippet from my service file:
sortByRankAndDates(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;
}
Your help would be greatly appreciated. Thank you!