-1

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

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Phil Glen
  • 24
  • 7
  • Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – pilchard Apr 08 '22 at 16:18

1 Answers1

2

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)
});
  • I have seen this on other posts. Unfortunately my returned array of objects seems to ignore the second argument. It's possibly an issue with my date formats. Appreciate your rapid response. – Phil Glen Apr 08 '22 at 17:59
  • cracked it by switching the order of the object being sorted: this.types.indexOf(b.type) - this.types.indexOf(a.type) Thanks for your help! – Phil Glen Apr 08 '22 at 18:10