Home > Mobile >  Swap two elements between two arrays in Javascript
Swap two elements between two arrays in Javascript

Time:03-17

Let's say I have two different arrays:

const a = ['a', 'b', 'c', 'd', 'e', 'f'];

and

const b = ['g', 'h', 'i', 'j', 'k', 'l'];

and I want to place 'c' on the position of 'l' and vice-versa, like so:

const a = ['a', 'b', 'l', 'd', 'e', 'f'];
const b = ['g', 'h', 'i', 'j', 'k', 'c'];

How can I archieve this?

I do it like this because I'm organizing a set of values in pages, and each page contains at max 6 elements

CodePudding user response:

You could use array destructuring for swapping elements.

const a = ['a', 'b', 'c', 'd', 'e', 'f'];
const b = ['g', 'h', 'i', 'j', 'k', 'l'];
let idxC = a.indexOf('c'), idxL = b.indexOf('l');
[a[idxC], b[idxL]] = [b[idxL], a[idxC]];
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));

CodePudding user response:

Another way to swap elements, kind of overengeniring but forgive me

const a = ['a', 'b', 'c', 'd', 'e', 'f'];
const b = ['g', 'h', 'i', 'j', 'k', 'l'];

const pair = ['c','l'];
const divider = '//';

const aa = a.join(divider).replaceAll(...pair).split(divider);
const bb = b.join(divider).replaceAll(...pair.reverse()).split(divider);

console.log(...aa);
console.log(...bb);
.as-console-wrapper{min-height: 100%!important; top: 0}

  • Related