Write a function chunk(arr, size) that splits an array into smaller sub-arrays of a specified length. For example, chunk([1, 2, 3, 4, 5], 2) should return [[1, 2], [3, 4], [5]].
function chunk(arr, size) {
// Your code here
}
Rules:
- Must return a new array of chunked arrays.
- The final chunk can contain fewer elements if the input array cannot be divided evenly.
- Do not use any external libraries.
Post your solution as a reply. Answer goes up in about a day.
A simple approach is to step through the array by the chunk size and use slice():
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
For example:
chunk([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]]
This keeps the original array unchanged and naturally handles the final smaller chunk.
nice, slicing is definitely a good way to approach this. we’ll see how close that gets you later today!