按角度对两个属性排序数组

时间:2018-02-23 13:37:24

标签: javascript arrays angular sorting

我如何先付款然后按角度金额排序?

在c#中,我可以轻松地array.orderBy(x => x.payment).thenby(x => x.amount)

角度有类似的东西吗?我正在探索Array.Sort()但没有我需要的东西。

我们还特别要求将payment4排序到最后一个。

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

1 个答案:

答案 0 :(得分:0)

您需要编写custom sort函数。

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;
    }
});