Seb*_*önn 1 javascript arrays sorting
我有一个要根据对象值排序的数组。
我的数组如下所示:
[
{
"name": "Ricard Blidstrand",
"number": "5",
"position": "b"
},
{
"name": "Gustaf Thorell",
"number": "12",
"position": "fw"
},
{
"name": "Rasmus Bengtsson",
"number": "13",
"position": "mv"
}
]
Run Code Online (Sandbox Code Playgroud)
我要按照位置键的顺序排序:
mv> b> fw
我需要像这样写吗,还是我错了?
if(a === "b" && b === "b") {
return 0;
} else if (a === "b" && b === "mv") {
return 1;
}
Run Code Online (Sandbox Code Playgroud)
您需要先指定优先级数组。
var priority = [ "mv", "b", "fw"];
Run Code Online (Sandbox Code Playgroud)
现在基于此对数组进行排序
arr.sort( ( a, b ) => priority.indexOf( a.position ) - priority.indexOf( b.position ) );
Run Code Online (Sandbox Code Playgroud)
演示版
var priority = [ "mv", "b", "fw"];
Run Code Online (Sandbox Code Playgroud)