这个问题已经在这里有了答案: > Javascript – sort array based on another array 18个
我有一个看起来像这样的数组:
order = [ "foo", "bar", "baz" ];
该数组包含我要对对象数组进行排序的属性值.我想对数据进行排序,以使所有名称为“ foo”的对象首先出现,然后是“ bar”,然后是“ baz”.我的对象数组看起来像这样:
data = [
{name: "foo", score: 8},
{name: "baz", score: 4},
{name: "baz", score: 9},
{name: "foo", score: 6},
{name: "bar", score: 9}
];
我想要数据顺序的结果看起来像这样,当名称相同时,数组按名称排序,也按score desc排序:
sortedData = [
{name: "foo", score: 8},
{name: "foo", score: 6},
{name: "bar", score: 9},
{name: "baz", score: 9},
{name: "baz", score: 4}
];
这是到目前为止我尝试过的代码:
order.forEach(name => {
sortedData = [...this.data].sort(function(obj1, obj2) {
return (
-(obj1.name) || obj2.score < obj1.score
);
});
});
console.log(sortedData);
解决方法:
您可以简单地使用sort和indexOf
let order = [ "foo", "bar", "baz" ];
let data = [
{name: "foo", score: 8},
{name: "baz", score: 4},
{name: "baz", score: 9},
{name: "foo", score: 6},
{name: "bar", score: 9}
];
let op = data.sort((a,b)=> (order.indexOf(a.name) - order.indexOf(b.name)) || b.score - a.score )
console.log(op)