Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda