在对象数组中对嵌套数组进行排序

时间:2016-05-25 10:01:47

标签: javascript underscore.js

我不知道为什么,但排序是编程的事情之一,每次都让我感到困惑......

我想在第一级对数组成员进行排序,以便所有具有 license:“truck”和active:true 属性的成员首先出现在列表中。然后,下一个成员应该是许可证:“car”和active:true

的所有成员

underscore.js是可用的......

java.io.FileNotFoundException: multidex.keep: open failed: EROFS (Read-only file system)

预期结果:

private void saveInMultidexKeepFile(List externalDexClasses) {
        if (externalDexClasses != null && externalDexClasses.size() > 0) {
            File file = new File("multidex.keep");
            FileOutputStream fOut = null;
            try {
                fOut = new FileOutputStream(file);
                OutputStreamWriter outWriter = new OutputStreamWriter(fOut);
                for (int i = 0; i < externalDexClasses.size(); i++) {
                    outWriter.append(externalDexClasses.get(i).toString());
                    outWriter.append("\n");
                    LOGD("Multidex:", outWriter.toString());
                }
                outWriter.close();
                fOut.close();


            } catch (FileNotFoundException e) {
                e.printStackTrace();
                LOGD("Multidex:", e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                LOGD("Multidex:", e.getMessage());
            }

        }

    }

3 个答案:

答案 0 :(得分:1)

如果有许多具有相同属性的人,则此类的复合键将是与排序顺序+名称相关的活动属性的总和。这给了:

sortOrder = {'truck':1 , 'car': 2}

result = _.sortBy(data, item => [
    _(item.properties)
        .filter(prop => prop.active)
        .map(prop => sortOrder[prop.licence])
        .sum()
    ,
    item.name]
).reverse();

答案 1 :(得分:1)

Array#sort和排序优先级的函数会有所帮助。

var arr = [{ 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 }, ] }];

arr.sort(function (a, b) {
    function max(r, a) {
        return Math.max(r, ({ truck: 2, car: 1 }[a.licence] || 0) + ({ true: 8, false: 4 }[a.active] || 0));
    }
    return b.properties.reduce(max, 0) - a.properties.reduce(max, 0);
})

console.log(arr);

答案 2 :(得分:1)

试试这个:

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())。 希望这能解决您的疑问.. :)