Home > Mobile >  4th argument in reduce
4th argument in reduce

Time:05-05

Here is the function:

 function chunk(array: number[], size: number): number[][] {
    return array.reduce((chunks, curr, _, arr) => {
        console.log(arr.length); // -> 10 which is correct

        // let len = arr.length; // -> Cannot read properties of undefined (reading 'length')

        let len = chunks.length; // this works
        if (len === 0 || chunks[len - 1].length === size) chunks.push([curr]);
        else chunks[len - 1].push(curr);
        return chunks;
    }, []);
}

    console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)); // ->[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]

The fourth argument to reduce is the array that we're iterating over. I can log it and I get the correct result (10) see above. But when I try to use it and assign it to a variable I get an error(see above). Could someone please shed some light?

CodePudding user response:

From Mozilla's page, the fourth paramater is the array that is being reduced. (The current state of the reduced array). You'll instead want to access the array variable that is already declared instead to avoid errors.

For example:

array.reduce(_, _, _, arr => {
  console.log(arr.length == array.length) // false, this is the reduced array.
})

The reason why you're getting the error is because the arr.length property isn't as what you expect.

  • Related