Home > Software design >  change index in one array in accordance with another one js
change index in one array in accordance with another one js

Time:12-26

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]

CodePudding user response:

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;
})

CodePudding user response:

You could sort by using the other array as index. If this daoes not work with real data, please andd a small amount of data to highlight the problem.

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

a.sort((l, r) => b[l - 1] - b[r - 1]);

console.log(...a);

  • Related