Search code examples
javascriptarrayssorting

How do I sort a nested array of strings and objects based on predetermined array of just strings?


I already searched and could not find the answer.

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"]];

Solution

  • Don't use sort for this. It's used when you need to compare the elements with each other to determine the relative order.

    You just need to loop over correct_order_arr, and find the corresponding elements in 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);