Chunk an array into fixed-size pieces
You have 47 product cards and a grid that shows three per row. Or 500 ids and an API that accepts 50 at a time. Both problems are the same problem: cut a flat array into consecutive pieces of a fixed size.
Implement chunk(items, size). items is an array and size is the maximum length of each piece. Return a new array of arrays, taking items in order: the first size items, then the next size, and so on. The final piece is shorter than size when the items do not divide evenly. If size is not an integer greater than zero, return an empty array. An empty items array returns an empty array. Never modify items.
What it has to do
- Return a new array of arrays, with items in their original order.
- The last chunk holds the remainder when the length does not divide evenly.
- Return
[]whensizeis not an integer of at least 1. - Return
[]for an empty input array. - Do not mutate the input array.
Where it's been asked
- Meta
From public interview reports — a problem very like this one has shown up in a round at these companies. Not an exhaustive list.
Stuck? The javascript course covers everything this challenge needs.
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
Need a nudge?
Reveal a conceptual hint or the reference solution. Both were written and reviewed with the problem — no runtime magic.
Discussion
Sign in to postNo comments yet. Be the first to say something.