Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading