AniUI Academy
easy+150 XPPractice

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 [] when size is not an integer of at least 1.
  • Return [] for an empty input array.
  • Do not mutate the input array.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.