2
votes

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?

2

2 Answers

2
votes

You could do this with nested loops, but why not go for a simpler approach and use array.slice()?

function chunk( input, size ) {
    var output = [];
    for( i = 0;  i < input.length;  i += size ) {
        output.push( input.slice( i, i + size ) );
    }
    return output;
}
2
votes

After

for(i = 0; i < arr.length; i++) {

you must initialize the one-dimensional array:

newArr[i] = [];

This will solve the error, but not produce the result you want. I think you need something like this:

for (i = 0; i < ceil(arr.length / size); i++) {
    newArr[i] = [];
    for (j = 0; j < size; j++) {
        if (i * size + j >= arr.length)
            break;
        newArr[i].push(arr[i * size + j]);
    }
}