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

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

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 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