Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

73
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!