2677. Chunk Array
Given an array arr and an integer size, split the array into chunks (subarrays), each of length size. The final chunk may be shorter if arr.length isn't evenly divisible by size.
📄 Problem Statement
Implement a function chunk(arr, size) that returns a new array, where each element is a chunk (subarray) of length size. Do not use Lodash’s _.chunk.
💡 Example
chunk([1, 2, 3, 4, 5], 2)
// âžž [[1, 2], [3, 4], [5]]
chunk([1, 9, 6, 3, 2], 3)
// âžž [[1, 9, 6], [3, 2]]
chunk([8, 5, 3, 2, 6], 6)
// âžž [[8, 5, 3, 2, 6]]
chunk([], 1)
// âžž []
🧠Explanation
You loop through the array and slice out subarrays of length size using a step increment of size. The final chunk may be shorter if there aren't enough remaining elements.
This is a clean way to group array elements without using external libraries.
✅ Your Solution
/**
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
var chunk = function(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
};