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 :

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;

Leave a Reply