1

好的,鉴于此输入(为简洁起见,已删除其他属性):

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

任何帮助将非常感激!

4

1 回答 1

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;
});
于 2013-11-25T00:18:13.320 回答