如何根据预定的字符串数组对字符串和对象的嵌套数组进行排序?

问题描述 投票:0回答:1

我已经搜索过但找不到答案。

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"]];
javascript arrays sorting
1个回答
1
投票

请勿为此使用

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);

© www.soinside.com 2019 - 2024. All rights reserved.