在JavaScript中对数组索引上的对象进行排序?

时间:2013-11-24 23:59:20

标签: javascript arrays sorting lodash

好的,所以给定这个输入(其他属性为了简洁而被剥离):

var names = [{
    name: 'Michael'
}, {
    name: 'Liam'
}, {
    name: 'Jake'
}, {
    name: 'Dave'
}, {
    name: 'Adam'
}];

我想用另一个数组的索引对它们进行排序,如果它们不在该数组中,则按字母顺序排序。

var list = ['Jake', 'Michael', 'Liam'];

给我一​​个输出:

Jake, Michael, Liam, Adam, Dave

我尝试过使用lo-dash,但这不太对劲:

names = _.sortBy(names, 'name');
names = _.sortBy(names, function(name) {
    var index = _.indexOf(list, name.name);
    return (index === -1) ? -index : 0;
});

输出为:

Jake, Liam, Michael, Adam, Dave

任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:3)

你很亲密。问题是return (index === -1) ? -index : 0;

按照您的方法,它应该如下所示:

names = _.sortBy(names, 'name')

var listLength = list.length;

_.sortBy(names, function(name) {
    var index = _.indexOf(list, name.name);
    // If the name is not in `list`, put it at the end
    // (`listLength` is greater than any index in the `list`).
    // Otherwise, return the `index` so the order matches the list.
    return (index === -1) ? listLength : index;
});