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"];
afterlooks like an alpha SORT not an index of the other array list. Is this supposed to be a trick question :)arrayToOrder[rank[i]] = temp[i];. If reordering an array according to "indexes", the key line of code isarrayToOrder[i] = temp[index[i]];. I don't know which case is more common, but one example of this is sorting an array of indexes 0 to length-1, according to another array, and in this case, the reorder is done according to indexes. You can convert indexes to rank :rank[index[i]] = i;or vice versaindex[rank[i]] = i;.