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

188
Views
How can I insert each of an arrays elements every other element in another array?

I have two arrays.

let a = [1, 3, 5, 7] let b = [2, 4, 6, 8]

I want the result: a = [1, 2, 3, 4, 5, 6, 7, 8]

How can I insert each of array B's elements every other element in array A?

I have tried using splice in a for loop, but the length of array A changes so I cannot get it to work.

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

0

You can create a new array, loop through a and push the current item and the item in b at the same index:

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = []
a.forEach((e,i) => res.push(e, b[i]))

console.log(res)

Alternatively, you can use Array.map and Array.flat:

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8];
let res = a.map((e,i) => [e, b[i]]).flat()

console.log(res)

about 4 years ago · Juan Pablo Isaza Report

0

If the arrays have the same length, then you can use flat map to avoid mutating the original array.

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

const res = b.flatMap((elem, index) => [a[index], elem]);

console.log(res);

about 4 years ago · Juan Pablo Isaza Report

0

You can try:

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b]

console.log(newArray) // [1, 3, 5, 7, 2, 4, 6, 8]

If you want to sort just

let a = [1, 3, 5, 7];
let b = [2, 4, 6, 8]
let newArray = [...a, ...b].sort((a, b) => a - b)

console.log(newArray) // [1, 2, 3, 4, 5, 6, 7, 8]
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!