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

return reordered version of array b based on reordered version of a

I have two arrays a and b like this:

const a = [1,2,3,4]
const b = ['1','2','3','4'] // could be 'a','b','c','d'

const reordered_a = [4,1,3,2] // based on this reordering 

function reorder_b() {
    // should return ['4','1','3','2']
} 

How can I return reordered version of b based on reordered positions in reordered_a?

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

>Solution :

You could take an object with the indices for the values and map the pattern with the values of the indices.

const a = [1, 2, 3, 4]
const b = ['1', '2', '3', '4'] // could be 'a','b','c','d'

const reordered_a = [4, 1, 3, 2] // based on this reordering 

function reorder_b() {
   const references = Object.fromEntries(Object.entries(a).map(a => a.reverse()));
   return reordered_a.map(k => b[references[k]]);
}

console.log(reorder_b()); // 4 1 3 2
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