Lesson 3 of 8

Splitting into chunks

Goal

A thousand items in batches of a hundred

01

Explanation

Paginating results, sending data in batches and laying out items in a three-column grid all come down to the same thing: splitting an array into groups of a fixed size.

The slice method does this without changing the original array: you move forward in steps of size and cut out one piece at each step.

The real test is the edge cases: an empty array, a size that doesn't divide the length evenly, and a size of zero or less. That last one makes the loop run forever if you don't check for it before the loop starts.

02

Your task

Write chunk(arr, size) to return an array of arrays, after first checking that the input is valid.

Checks

6 checks
  1. Splits into equal chunks correctly
  2. The shorter last chunk isn't lost
  3. An empty array returns an empty array
  4. A size of zero doesn't freeze the page
  5. A negative size doesn't freeze the page either
  6. The original array is unchanged
03

Hints

0/3
Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.