typestar

Chunk an array in JavaScript

Splits an array into fixed-size pieces, for batching requests or laying out a grid.

function chunk(items, size) {
  if (size < 1) throw new Error("size must be positive");
  const out = [];
  for (let i = 0; i < items.length; i += size) {
    out.push(items.slice(i, i + size));
  }
  return out;
}

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
200
Tokens
66
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 44 seconds.

Type this snippet

Step 4 of 10 in Arrays, step 20 of 43 in Language basics.

← Previous Next →

Chunk an array in other languages