我有一个数组,我想根据我的对象上的值对其进行排序。
我的数组看起来像这样:
[
{
"name": "Ricard Blidstrand",
"number": "5",
"position": "b"
},
{
"name": "Gustaf Thorell",
"number": "12",
"position": "fw"
},
{
"name": "Rasmus Bengtsson",
"number": "13",
"position": "mv"
}
]
我想按照position-key的顺序排序:
mv > b > fw
我需要这样写吗,还是我写错了?
if(a === "b" && b === "b") {
return 0;
} else if (a === "b" && b === "mv") {
return 1;
}
需要先指定优先级数组。
var priority = [ "mv", "b", "fw"];
现在根据这个对你的数组进行排序
arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );
演示
var arr = [{
"name": "Ricard Blidstrand",
"number": "5",
"position": "b"
},
{
"name": "Gustaf Thorell",
"number": "12",
"position": "fw"
},
{
"name": "Rasmus Bengtsson",
"number": "13",
"position": "mv"
}
];
var priority = [ "mv", "b", "fw"];
arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );
console.log(arr);