Home > database >  Swap elements in two arrays
Swap elements in two arrays

Time:10-30

Say I have these two lists (could be of different sizes):

const a = [0,1,3];
const b = [7,2,6,4];

say I want to swap element 1 of a, with element 3 of b? what's the easiest way to do this?

AKA, I am looking to do this:

swap(1, a, 3, b) => { a: [0,4,3], b: [7,2,6,1] }

CodePudding user response:

If you want a one liner

const swap = (p1, a1, p2, a2) => [a1[p1],a2[p2]] = [a2[p2], a1[p1]];

const a = [0,1,3];
const b = [7,2,6,4];
swap(1, a, 3, b)
console.log(a, b);

CodePudding user response:

function swap(i, a, j, b) {
  const t = a[i]
  a[i] = b[j]
  b[j] = t
}
  • Related