FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Fix off-by-one in `chunk`

Fix off-by-one in `chunk`

easy
By FrontendAtlas Editorial · Updated Mar 31, 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.
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)          // []

Solution

Overview

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;

}

Similar questions

Fix numeric sort in `sortScores`easyStop mutating caller data in `unique`easyFix missing return in `map` / `filter`easy

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
← Prev←5 / 8Next →→