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

change index in one array in accordance with another one js

I need to change indexes of elements in arr a due to their indexes in arr b.

const a = [4,3,2,1,5];
const b = [1,2,3,4,5];

console.log(a)  [1,2,3,4,5]

>Solution :

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

If you mean ordering array a according to array b, then you can do like this:

a.forEach((element,i) => {
    // first get the index of a[i] from array b
    const index = b.indexOf(a[i])
    
    // then swap them
    const temp = a[index];
    a[index] = a[i];
    a[i] = temp;
})
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