Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda