Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript, partially reordering array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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 in order, or otherwise by the index itself + order.length.

We add order.length so that something at index 1 in order appears before something not in order that is at index 0 in arr.

Then, map the indices to the elements of arr

const before = [23, 21, 14, 12, 10, 8, 15]
const indexes = [2,1,4,0];

const reorderByIndexes = (arr, order) => {
  const f = i => {
    let r = order.indexOf(i)
    return r!==-1 ? r : i + order.length
  }
  return arr.map((_,i) => i).sort((i,j) => f(i) - f(j)).map(i => arr[i])
}

const after = reorderByIndexes(before, indexes)

console.log(after.join());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading