What is the best way to partially re-order an array?
I have created a very basic example;
Basically I want to reorder the array (before) using the (indexes) stored in the array.
Using the code I have outputs: 14,21,10,13.
However I would like to then keep the remainder of the array that isn’t included added to the new after array in the order they originally appear.
This would leave the after array populated as the following: 14,21,10,13 23,8,15
const before = [23, 21, 14, 12, 10, 8, 15]
const indexes = [2,1,4,0];
const reorderByIndexes = (arr, order) => order.map((index) => arr[index]);
const after = reorderByIndexes(before, indexes);
console.log(after.join());
// 14,21,10,13 23,8,15
I know on a simplistic example like this I could use a loop to iterate over them but the final version is set to be a lot larger.
3
Answers
I’m assuming there is a typo in your question, and the expected output is
14,21,10,23,12,8,15
Order the indices of
arr
by either the position of the index inorder
, or otherwise by the index itself +order.length
.We add
order.length
so that something at index 1 inorder
appears before something not inorder
that is at index 0 inarr
.Then, map the indices to the elements of
arr
To make it efficient, just pre-allocate the array and fill its 2 halves:
And a benchmark:
You could sort the indices and build an object for getting new indices.
Finally map the values by source index or the actual index.