Daniel Corona
Daniel Corona

Reputation: 1222

Swap two elements between two arrays in Javascript

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 achieve this?

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

Upvotes: 2

Views: 1257

Answers (2)

A1exandr Belan
A1exandr Belan

Reputation: 4780

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}

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89139

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

Upvotes: 2

Related Questions