I have an array and I’m trying to re-order this array based on another array. The second array is an array of indexes (see below). I’m looking to build a clean function to take two arguments (an array and an array of indexes), and return the re-ordered array. I've tried to build this function and have an example below, however it's not returning what I'm expecting. Any help is greatly appreciated.
var before = ["T", "T", "A", "T", "T", "T", "T", "T", "A", "T", "T","T", "W", "W", "W", "W", "T", "T", "T", "T", "T", "W", "T"];
var indexes = [8, 2, 11, 22, 0, 4, 5, 18, 6, 17, 16, 19, 7, 3, 20, 1, 10, 9, 14, 13, 21, 12, 15];
// Attempt
function reorderArray(arrayToOrder ,order){
// Get a copy of the array we want to change
var temp = arrayToOrder
// loop through the indexes
// use the indexes to place the items in the right place from the copy into the original
for(let i = 0; i < arrayToOrder.length; i++) {
console.log("arr: ", arrayToOrder[order[i]] );
console.log("temp: ", temp[i] );
arrayToOrder[order[i]] = temp[i];
}
return arrayToOrder;
}
// run function
reorderArray( before, indexes );
// function should return this array
var after = ["A", "A", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "W", "W", "W", "W", "W"];