UnderscoreJs:_.groupBy与_.sortBy一起

时间:2014-05-14 12:08:38

标签: javascript underscore.js

我尝试在成对中使用下划线_.groupBy()_.sortBy,问题是最后一个使用从groupBy返回的键将对象更改为带索引的数组。是否可以保留对象的原始索引(键)?

以下是示例:

我的代码:

var sorted = _.chain(cars).groupBy('Make').sortBy(function(car) {
    return car.length * -1;
});

来自groupBy的结果:

{ 
    "Volvo" : [ "S60", "V40" ],
    "Volkswagen" : [ "Polo", "Golf", "Passat" ]
}

来自sortBy的结果:

[ 
    0 : [ "Polo", "Golf", "Passat" ],
    1 : [ "S60", "V40" ]
]

预期结果:

[
    "Volkswagen" : [ "Polo", "Golf", "Passat" ],
    "Volvo" : [ "S60", "V40" ]
]

1 个答案:

答案 0 :(得分:4)

对象在JavaScript中是无序的。如果您需要像对象这样但有序的东西,您可以使用_.pairs进行转换,然后对对列表进行排序。

_.pairs({ 
    "Volvo" : [ "S60", "V40" ],
    "Volkswagen" : [ "Polo", "Golf", "Passat" ]
})

给出:

[
    ["Volvo", [ "S60", "V40" ]],
    ["Volkswagen", [ "Polo", "Golf", "Passat" ]]
]

...然后您可以使用_.sortBy进行排序。如果您将上述内容分配给cars,那么:

_.sortBy(cars, function(x) { return -x[0].length; });

给出:

[
    [ 'Volkswagen', ['Polo', 'Golf', 'Passat' ]],
    [ 'Volvo', ['S60', 'V40']]
]