我不知道为什么,但是排序是每次让我感到困惑的编程问题之一。

我想在第一层对数组成员进行排序,以便所有具有属性licence:“ truck”和active:true的成员首先出现在列表中。然后,下一个成员应该是所有拥有执照的会员:“汽车”,活跃会员:true

underscore.js可用...

[
        {
            name: 'Denes',
            properties: [
                {
                    licence: "car",
                    active: true
                },
                {
                    licence: "truck",
                    active: false
                },
            ]
        },
        {
            name: 'Patrick',
            properties: [
                {
                    licence: "car",
                    active: false
                },
                {
                    licence: "truck",
                    active: true
                },
            ]
        },
        {
            name: 'Marc',
            properties: [
                {
                    licence: "car",
                    active: false
                },
                {
                    licence: "truck",
                    active: false
                },
            ]
        }
    ]


预期结果:

[

        {
            name: 'Patrick',
            properties: [
                {
                    licence: "car",
                    active: false
                },
                {
                    licence: "truck",
                    active: true
                },
            ]
        },
        {
            name: 'Denes',
            properties: [
                {
                    licence: "car",
                    active: true
                },
                {
                    licence: "truck",
                    active: false
                },
            ]
        },
        {
            name: 'Marc',
            properties: [
                {
                    licence: "car",
                    active: false
                },
                {
                    licence: "truck",
                    active: false
                },
            ]
        }
    ]

最佳答案

尝试这个:

function comparator(){
    return function(a, b){
        return weightage(b)- weightage(a);
    }
};

function weightage(obj){
    var maxWeight = -1;
    for (var i in obj.properties){
        if(obj.properties[i].licence == 'truck' && obj.properties[i].active) {
            maxWeight = 1;
            return maxWeight;
        } else if (obj.properties[i].licence == 'car' && obj.properties[i].active) {
            maxWeight = 0;
        }
    }
    return maxWeight;
};


假设您的数组名为:arr调用arr.sort(comparator())
希望这可以解决您的查询.. :)

07-28 02:50
查看更多