Home > OS >  Nested forEach does not work as expected in Javascript
Nested forEach does not work as expected in Javascript

Time:10-17

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?

CodePudding user response:

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])))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related