-3

How can I sort first by the payment then by the amount in angular?

In c#, I can easily do array.orderBy(x => x.payment).thenby(x => x.amount)

Is there a similar thing in angular? I was exploring the Array.Sort() but does not have what I need.

We also have a special requirement to sort payment4 to the last.

   array = [
    { payment: 'payment1', description:'desc1', place:'place1', amount: 1 },
    { payment: 'payment1', description:'desc1', place:'place2', amount: 10 },
    { payment: 'payment3', description:'desc3', place:'place3', amount: 17 },
    { payment: 'payment4', description:'desc4', place:'place4', amount: 14 },
    { payment: 'payment4', description:'desc4', place:'place4', amount: 51 },
    { payment: 'payment5', description:'desc5', place:'place5', amount: 31 },
    { payment: 'payment1', description:'desc1', place:'place1', amount: 111 },
    { payment: 'payment1', description:'desc1', place:'place2', amount: 71 },
    { payment: 'payment3', description:'desc3', place:'place3', amount: 17 },
    { payment: 'payment4', description:'desc4', place:'place4', amount: 21 },
    { payment: 'payment4', description:'desc4', place:'place4', amount: 18 },
    { payment: 'payment5', description:'desc5', place:'place5', amount: 123 }
    ]
ove
  • 3,092
  • 6
  • 34
  • 51

1 Answers1

0

You need to write a custom sort function.

array.sort(function (a, b) {
    if(a.payment == b.payment) {
        return (a.amount < b.amount) ? -1 : (a.amount > b.amount) ? 1 : 0;
    } else if (a.payment == 'payment4' && b.payment != 'payment4') {
        return 1; 
    } else if (a.payment != 'payment4' && b.payment == 'payment4') {
        return -1;
    } else {
        return (a.payment < b.payment) ? -1 : 1;
    }
});
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59