Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!