如何使用 lodash 按过滤值对对象进行排序?
// this is coming from select
var filtered_values = [99, "female"];
// this is my data
var data = [
{ name: "John Doe", age: 24, gender: "male" },
{ name: "Jona Yap", age: 27, gender: "female" }, // matching: female
{ name: "Einstein", age: 99, gender: "male" } // matching: 99
];
// How to sort on this by the values
data = _.sortby(data, filtered_values);
我想对列表进行排序,因为过滤后的值为 99 和女性,因此所有值为 99 和|或女性的对象都应位于顶部。
最佳答案
如果您只需要查找符合所有条件的内容,您可以使用 _.filter
:
_.filter(data, {gender: 'male', age: 99})
但是您的要求似乎更复杂。让我们编写一个函数来为对象分配分数并按分数对它们进行排序:
// I use the fact that when you add booleans they get converted to numbers.
function score(x) { return (x.gender === 'female') + (x.age === 99); }
或者,如果您不知道要匹配哪些字段,您可以这样做:
function score(x) { return _.includes(x, 'female') + _.includes(x, 99); }
或者以通用的方式:
var query = [99, "female"];
function score(x) {
return _.sum(query, function(y) { return _.includes(x, y); };
}
然后你可以使用_.orderBy
按分数对列表进行排序:
_.orderBy(data, score, 'desc')
结果:
关于javascript - 按相关性排序 : How to sort a list to have matching values first?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35316079/