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

214
Visualizações
Nested forEach does not work as expected in Javascript

I'm having a problem with this function, which should work the same way as Lodash _.zip([arrays])

In a nutshell, zip(['a', 'b'], [1, 2], [true, false]); shall return [['a', 1, true], ['b', 2, false]]

My function:

function zip(...array) {
  const newArr = Array(array[0].length).fill([]);
  array.forEach((el, i) => {
    el.forEach((item, idx) => {
      //   newArr[idx][i] = item;
      newArr[idx].push(item);
    });
  });
  return newArr;
}

Instead, it returns: [ [ 'a', 'b', 1, 2, true, false ], [ 'a', 'b', 1, 2, true, false ] ]

What could be written wrong?

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

0

When you call fill you are filling the array with the same array, so when you push to the array at index 0, you are also pushing to the array at index 1. You can solve this by first filling the array, then calling map.

You should also be looping through each item in the new array, then looping through each parameter and getting the item at the index of the outer loop.

function zip(...array) {
  const newArr = Array(array[0].length).fill().map(u => ([]));
  newArr.forEach((item, i) => {
    array.forEach((a) => {
      item.push(a[i])
    })
  })
  return newArr;
}

console.log(JSON.stringify(zip(['a', 'b'], [1, 2], [true, false])))

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