Write a function chunk(arr, size) that splits an array into groups of length size and returns them as a two-dimensional array. If the array cannot be split evenly, the final chunk should contain the remaining elements. For example, chunk([1, 2, 3, 4, 5], 2) should return [[1, 2], [3, 4], [5]].
function chunk(arr, size) {
// your code here
}
Rules:
Return an empty array if the input array is empty.
Assume size is always an integer greater than 0.
Do not mutate the original input array.
Post your solution as a reply. Answer goes up in about a day.
This is a classic problem. I remember a similar one from a data visualization project where I needed to group data points for a small multiples chart.
function chunk(arr, size) {
if (arr.length === 0) {
return [];
}
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
Challenge solution: The task is to implement a function that splits an array into chunks of a specified size.
One way to do it:
function chunk(arr, size) {
if (arr.length === 0) {
return [];
}
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
Why:
This solution iterates through the input array using a for loop, incrementing the index by ‘size’ in each step. In each iteration, it uses the ‘slice’ method to extract a sub-array from the current index up to ‘index + size’, effectively creating a chunk. These chunks are then pushed into a ‘result’ array, which is returned at the end, fulfilling the requirement of not mutating the original array.