[英]Sort an object on indices of an array in JavaScript?
OK so given this input (other properties have been stripped for brevity): 好的,所以给定此输入(为简洁起见,已剥离其他属性):
var names = [{
name: 'Michael'
}, {
name: 'Liam'
}, {
name: 'Jake'
}, {
name: 'Dave'
}, {
name: 'Adam'
}];
I'd like to sort them by another array's indices, and if they aren't in that array, sort alphabetically. 我想用另一个数组的索引对它们进行排序,如果它们不在该数组中,则按字母顺序排序。
var list = ['Jake', 'Michael', 'Liam'];
Giving me an output of: 给我一个输出:
Jake, Michael, Liam, Adam, Dave
I've tried using lo-dash but it's not quite right: 我尝试过使用lo-dash,但这不太对劲:
names = _.sortBy(names, 'name');
names = _.sortBy(names, function(name) {
var index = _.indexOf(list, name.name);
return (index === -1) ? -index : 0;
});
as the output is: 作为输出是:
Jake, Liam, Michael, Adam, Dave
Any help would be really appreciated! 任何帮助将非常感激!
You are close. 你很亲密
return (index === -1) ? -index : 0;
is the problem. 是问题。
Following your approach, it should look like this: 按照您的方法,它应该如下所示:
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.