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

155
Views
Can't seem to identify the issue (splitting an array in chunks)

So this function is supposed to split the array into chunks the size of the second argument, e.g. [1, 2, 3, 4] with the second argument 2 would return [[1, 2], [3, 4]], if the number is 3 it would return [[1, 2, 3], [4]] and so on. My function seems to be behaving in a similar way but it only returns the first chunk, and the subsequent chunks are just empty arrays. I increase the index by by the second argument after each iteration, so I'm not sure why it's not working. Can someone please explain what exactly is happening here and where is the error in the logic?

let arr = [1, 2, 3, 4, 5, 6]

function test(arr, num) {
    let idx = 0;
    let newArr = []
    while (idx < arr.length) {
      newArr.push(arr.slice(idx, num))
      idx = idx + num
    }
    return newArr
}

console.log(test(arr, 2))

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

0

You need an index as second parameter of Array#slice, instead of the length of slice.

For example if you take the second array, index = 2 and the second parameter has to be 4, the index of the end for slicing.

                     chunks
values   1 2 3 4 5 6
indices  0 1 2 3 4 5
slice    0 2           1 2
             2 4       3 4
                 4 6   5 6   

function test(arr, num) {
    let idx = 0;
    let newArr = [];
    while (idx < arr.length) {
        newArr.push(arr.slice(idx, idx += num));
    }
    return newArr;
}

let arr = [1, 2, 3, 4, 5, 6];

console.log(test(arr, 2));

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!