DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 30

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
}
Enter fullscreen mode Exit fullscreen mode

Create a copy of the array, so that the data isn't overwritten too early.

const copy = items.slice();
Enter fullscreen mode Exit fullscreen mode

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];
}
Enter fullscreen mode Exit fullscreen mode

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]
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)