The task is to reorder an array, given that we have an array of items and another array of indexes, so that A[i] is put at the index B[i].
The boilerplate code:
function sort(items, newOrder) {
// reorder items inline
}
Create a copy of the array, so that the data isn't overwritten too early.
const copy = items.slice();
For each index in the copied array, move the item in that index to the original array, based on the index of the second array.
for (let i = 0; i < newLength.array; i++) {
items[newOrder[i]] = copy[i];
}
The final code for the sort function:
function sort(items, newOrder) {
// reorder items inline
const copy = items.slice();
for(let i = 0; i < newOrder.length; i++) {
items[newOrder[i]] = copy[i]
}
}
That's all folks!
Top comments (0)