I am working through a javascript problem that asks me to:
Write a function that splits an array (first argument) into groups the length of size (second argument) an
The problem is that you are both advancing i
by size
at each iteration and removing size
elements from position i
. This causes you to skip processing every other chunk. Also, your continuation condition should be i < arr.length-size
; as it is, you would need to test for an empty temp
before pushing it after the loop exits. Try rewriting your loop as:
for (i = 0; i < arr.length-size;){
newArray.push(arr.slice(i,i+size));
temp.splice(i,size);
}
Since i
is always at 0, the loop can be simplified to:
while (arr.length > size) {
newArray.push(arr.slice(0,size));
temp.splice(0,size);
}