For what its worth, this style isn’t great.
Here is the code with a nicer style. You really want to use a while loop here.
for (let i = 0; i < arr.length;))
is bad form for two reasons:
- You want to explicitly include an iteration update (even if there isn’t one)
- If you aren’t updating your iterator, then you almost certainly don’t want a
for
loop
In this code below, the splice
actually removes size
elements from the array arr
, starting at index 0
.
// ----------------------------------------------------------
// While loop version
// ----------------------------------------------------------
function chunkArrayInGroups(arr, size) {
// Start with empty array
let newArr = [];
// Splice array into chunks
while (arr.length) {
newArr.push(arr.splice(0, size));
}
// Return result
return newArr;
}
// ----------------------------------------------------------
// Output while loop version
// ----------------------------------------------------------
console.log("----- While loop version -----");
console.log("Here we use arr.splice(start, size)");
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
In this example, size = 2
. Inside the first while
loop iteration, the first two elements, [a, b]
, are removed. The array arr
still has elements, so arr.length
is still truthy and we remove the new first two elements [c, d]
. Now the array arr
is empty and arr.length
is falsey, so the loop ends and the new array newArr
is returned.
This version of the code is better. You don’t want to change input arrays if you can avoid it.
// ----------------------------------------------------------
// For loop version
// ----------------------------------------------------------
function chunkArrayInGroups(arr, size) {
// Start with empty array
let newArr = [];
// Slice array into chunks
for (let i = 0; i < arr.length; i += size) {
newArr.push(arr.slice(i, i + size));
}
// Return result
return newArr;
}
// ----------------------------------------------------------
// Output for loop version
// ----------------------------------------------------------
console.log("----- For loop version -----");
console.log("Here we use arr.slice(start, stop)");
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
In this example, again size = 2
. Inside the first for
loop iteration, we slice out the elements from 0
to 2
, [a, b]
, and copy them into the new array. We then increment our iterator by size
. i
is now 2
, which is still not past the end of the array, and we slice out the elements from 2
to 4
, [c, d]
, and copy them into the new array. On the next iteration, i
is no longer less than the length of the original array, so the loop ends and the new array newArr
is returned.
Also, indentation and braces are your friend. They keep your code clearer and better organized.