Home > Net >  Can't seem to identify the issue (splitting an array in chunks)
Can't seem to identify the issue (splitting an array in chunks)

Time:05-14

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))

CodePudding user response:

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));

  • Related