Home > front end >  Sort by Date and OrderBy external Array
Sort by Date and OrderBy external Array

Time:04-09

I have an Array of Objects like this:

[{
  date: 2022-04-07T01:00:00.000 00:00,
  type: 'profit'
  amount: 200
},{
  date: 2022-04-07T01:00:00.000 00:00,
  type: 'withdraw'
  amount: 600
},{
  date: 2022-04-07T01:00:00.000 00:00,
  type: 'invest'
  amount: 900
},{
  date: 2022-04-08T01:00:00.000 00:00,
  type: 'deposit'
  amount: 200
},{
  date: 2022-04-08T01:00:00.000 00:00,
  type: 'profit'
  amount: 200
}]

In the datasource the dates are not in order so I am sorting by date like this:

this.allTransactions.sort((a: any, b: any) => {
  return new Date(b.date).getTime() - new Date(a.date).getTime();
});

However I need to also sort any objects with the same date by an external array:

['invest', 'withdraw', 'profit']

I'm struggling with the second part sorting the date groups already sorted by the order in the array. this.allTransactions is in an *ngFor loop in Angular 12

CodePudding user response:

You can add an extra condition after your current one, which will be used if the first one resolves as 0

const typeOrder = ['invest', 'withdraw', 'profit']

transactions.sort((a, b) => {
  return new Date(b.date).getTime() - new Date(a.date).getTime() || typeOrder.indexOf(a.type) - typeOrder.indexOf(b.type)
});
  • Related