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

240
Visualizações
Inserted array shows in reverse JS

I am just starting to learn js and as many (I'm sure) I am facing problems lol. I am trying to copy an array into another array at a designated index location.

I seem to be able to do everything correct but when I log the result, the inserted array shows in reverse and I have no idea why¿?¿?.

Have also tried a .forEach as looping method, but I'm still a bit green to use it right.

This is the code:

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2.slice([]);
  for (let i = 0; i < arr1.length; i++) {
    newArr.splice(n, 0, arr1[i]);
    console.log(newArr)
  }
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

It logs // [ 4, 3, 2, 1, 5, 6 ] instead of the desired out: [ 4, 1, 2, 3, 5, 6 ]

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are inserting the elements at the same index, so after inserting 1 you insert 2 at the same position, shifting back the 1 and all following elements. Either iterate backwards over arr1 or increment n after each iteration like I have done here.

function frankenSplice(arr1, arr2, n) {
  let newArr = arr2.slice([]);
  for (let i = 0; i < arr1.length; i++) {
    newArr.splice(n, 0, arr1[i]);
    console.log(newArr)
    n++; // add this
  }
}

frankenSplice([1, 2, 3], [4, 5, 6], 1);

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