2

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 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

can someone explain why there's a break on line 5?
Suppose size = 3, but the original arr has 7 members. The last 'chunk' will contain only 1 element - after that, there will be no more members to fill the remaining 2 spots in the last chunk. This is where the break comes in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.