Fix off-by-one in `chunk`

easy
By FrontendAtlas Editorial · Updated Oct 5, 2026
A teammate wrote chunk(arr, size) to split rows into smaller batches. It looks fine at first glance, but the loop boundary is slightly off: exact divisions can produce an extra empty chunk, and an empty input can come back as [[]]. Fix the bug without changing the function's contract.

Solution idea

export default function chunk(arr, size){

if(!Array.isArray(arr) || size <= 0) return [];

const out = [];

// Stop before arr.length so we never push a trailing empty slice.

for(let i = 0; i < arr.length; i += size){

out.push(arr.slice(i, i + size));

}

return out;

}

Examples
chunk([1,2,3,4,5], 2) // [[1,2],[3,4],[5]]

chunk([1,2,3,4], 2)   // [[1,2],[3,4]]

chunk([], 3)          // []