I'm trying to solve this problem: Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array. For example:
chunk(['a', 'b', 'c', 'd'], 2)
should return
[['a'. 'b'], ['c', 'd']]
My code is as follows:
function chunk(arr, size) {
var newArr = [[]];
for(i = 0; i < arr.length; i++) {
for(j = 0; j < size; j++) {
newArr[i].push(arr[i + j]);
}
}
return newArr;
}
It gives an error: Cannot read property 'push' of undefined. Why is this happening and how can I fix this?