Lauren
Lauren

Reputation: 109

Why is my Javascript for loop not looping?

I'm trying to write a for loop that splits an array (parameter: arr) into sub-arrays of a given size (parameter: size), but it seems to be exiting the for loop early/not actually looping back in.

This code should return [['a', 'b'] ['c', 'd']], but right now is only returning [['a', 'b']].

I've tried researching but I can't pinpoint what in my code is stopping the loop from going back through the array.

function chunkArrayInGroups(arr, size) {
  var newArr = [
    []
  ];
  for (var i = 0; i < arr.length; i++) {
    newArr[0].push(arr.shift(arr.slice(i, size)));
  }
  return newArr;
}

//calling the function:
console.log(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2));

Please help me figure this out.

Upvotes: 0

Views: 3339

Answers (3)

Barmar
Barmar

Reputation: 781096

You're modifying the array while you're looping over it, because arr.shift() removes the first element from the array and returns that. You're pushing that removed element onto newArr[0], not the slice.

So on the first iteration of the loop, arr is:

['a', 'b', 'c', 'd']

You push 'a' onto the result array, remove it from arr, and increment i.

On the next iteration, arr is

['b', 'c', 'd']

You push 'b' onto the result array, remove it from arr, and increment i.

On the next iteration, arr is

['c', 'd']

i is now 2, which is not less than arr.length, so the loop ends.

There's no reason to use arr.shift(), just use arr.slice() to get the chunks. You need to iterate by the chunk size, not 1. And the second argument to slice() is the end position (non-inclusive), not the size, so you need to add i + size.

function chunkArrayInGroups(arr, size) {
  var newArr = [
    []
  ];
  for (var i = 0; i < arr.length; i += size) {
    newArr[0].push(arr.slice(i, i+size));
  }
  return newArr;
}

//calling the function:
console.log(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2));

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You could use a while loop and check the position against the length of the array.

function chunkArrayInGroups(array, size) {
    var result = [],
        i = 0;

    while (i < array.length) {
        result.push(array.slice(i, i += size));
    }

    return result;
}

console.log(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191986

In the for loop increment i with size. On each iteration slice an array of length size (between i and i + size), and push it to newArr:

function chunkArrayInGroups(arr, size) {
  var newArr = [];
  for (var i = 0; i < arr.length; i += size) {
    newArr.push(arr.slice(i, i + size));
  }
  return newArr;
}

//calling the function:
console.log(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2));

Upvotes: 0

Related Questions