我有一个看起来像这样的数组:
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}
];
我希望结果的数据顺序看起来像这样,当数组名称相同时,数组按名称排序,但也按分数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);
答案 0 :(得分:1)
使用索引基于顺序进行排序,可以使用Array#indexOf
方法获取索引。要根据数字排序,只需返回差值即可。
// extract object properties for comparing
// return difference of indexes to sort based on that
// in case indexes are same return difference of score(to sort element with same name)
data.sort(({ name: a, score: as }, { name: b ,score: bs}) => order.indexOf(a) - order.indexOf(b) || bs - as)
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
}
];
data.sort(({ name: a, score : as }, { name: b ,score:bs}) => order.indexOf(a) - order.indexOf(b) || bs - as)
console.log(data)
答案 1 :(得分:1)
您可以简单地使用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)
答案 2 :(得分:0)
我们可以使用order数组中的数组索引进行排序。
还使用对象解构分配来获取对象键以进行比较。
如果name
键的第一次比较导致两个键相等,则使用score
键的第二个条件。
在我的回答中,我没有 变异 原始数组,如果需要这种行为,则可以检查以下解决方案:
const order = [ "foo", "bar", "baz" ];
const data = [
{name: "foo", score: 8},
{name: "baz", score: 4},
{name: "baz", score: 9},
{name: "foo", score: 6},
{name: "bar", score: 9}
];
function sortArray(data, order){
const sortedArr = Array.from(data).sort(({name: name1, score: score1},{name: name2, score: score2}) =>{
return name1 === name2 ? score2 - score1 : order.indexOf(name1) - order.indexOf(name2);
});
return sortedArr;
}
console.log("***Sorted Array***");
console.log(sortArray(data, order));
console.log("***Original Array***");
console.log(data);