我已经搜索过但找不到答案。
let correct_order_arr = ["dsihdlepsn", "dxuwmcbdeu", "dqpoimndxcv", "dplaeitfvse", "drtbnmjhfw", "ddrnvuqasw", "dfpotbnmjk", "dauiopmvdf", "drvbumnbvc"]
let starting_array = [[my_object_1,"dsihdlepsn"], [my_object_2,"dxuwmcbdeu"], [my_object_3,"dqpoimndxcv"], [my_object_4,"dplaeitfvse"], [my_object_5,"dfpotbnmjk"], [my_object_6, "drtbnmjhfw"], [my_object_7, "ddrnvuqasw"], [my_object_8, "dauiopmvdf"], [my_object_9, "drvbumnbvc"]];
let desired_arr = starting_array.sort(function (a,b){
if (correct_order_arr[a] === starting_array[a][1]){
return 0;
} else {
return 1;
}
})
//desired_arr = [[my_object_1,"dsihdlepsn"], [my_object_2,"dxuwmcbdeu"], [my_object_3,"dqpoimndxcv"], [my_object_4,"dplaeitfvse"], [my_object_6, "drtbnmjhfw"], [my_object_7, "ddrnvuqasw"], [my_object_5,"dfpotbnmjk"], [my_object_8, "dauiopmvdf"], [my_object_9, "drvbumnbvc"]];
请勿为此使用
sort
。当您需要相互比较元素以确定相对顺序时使用它。
只需循环
correct_order_arr
,在starting_array
中找到对应的元素即可。
let correct_order_arr = ["dsihdlepsn", "dxuwmcbdeu", "dqpoimndxcv", "dplaeitfvse", "drtbnmjhfw", "ddrnvuqasw", "dfpotbnmjk", "dauiopmvdf", "drvbumnbvc"]
let starting_array = [
["my_object_1", "dsihdlepsn"],
["my_object_2", "dxuwmcbdeu"],
["my_object_3", "dqpoimndxcv"],
["my_object_4", "dplaeitfvse"],
["my_object_5", "dfpotbnmjk"],
["my_object_6", "drtbnmjhfw"],
["my_object_7", "ddrnvuqasw"],
["my_object_8", "dauiopmvdf"],
["my_object_9", "drvbumnbvc"]
];
result_array = correct_order_arr.map(s => starting_array.find(el => el[1] == s));
console.log(result_array);