Split an array into chunks
Build consecutive chunks without changing the original array.
function chunk({ values, size }) { return Array.from({ length: Math.ceil(values.length / size) }, (_, i) => values.slice(i * size, (i + 1) * size)); }
Input & expected output
Input
{
"values": [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
],
"size": 5
}Expected output
[
[
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
],
[
"[email protected]",
"[email protected]"
]
]The edge case
Input
{
"values": [],
"size": 3
}Expected output
[]Know the limits
- Size must be an integer from 1 to 1,000; zero is rejected before allocation.
- Chunks are shallow copies. The final chunk may be shorter.
- Example: Oveyon’s POST /v1/send accepts up to 5 recipients (to + cc + bcc) per message. Give each batch its own idempotency key; reusing one key returns the first batch’s message instead of sending the second.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Split an array into chunks from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Curated implementation; explicit input bounds, edge cases, local fixtures and rebuilt presentation. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.