Skip to content
Advertisement

4th argument in reduce

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?

Advertisement

Answer

From Mozilla’s page, the fourth parameter is the array that is being reduced. You should access the array variable that is already declared, but the fourth parameter works.

For example:

array.reduce((_, __, ___, arr) => {
  console.log(arr.length == array.length) // true, this is the source array
});

The reason why you’re getting the error is not because of the arr.length property, but rather the way you’re accessing chunks.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement