Lodash _.chunk() method
What you’ll learn
- What
_.chunk(array, size)returns and when to use it. - How the last chunk behaves when the length is not a multiple of
size. - How to import
chunkwithout pulling in all of Lodash. - Open each numbered example in the Try it editor (
?tryit=1,2,3) with Lodash loaded from a CDN. - Practical pitfalls around size and empty arrays.
Prerequisites
Comfort with JavaScript arrays and a project where you can run small snippets (browser console or Node).
- You know what an array literal is and that indexes start at
0. - You can
npm install lodashor already have Lodash available in your app.
Overview
_.chunk splits an array into consecutive groups of size elements. The result is an array of smaller arrays. If elements do not divide evenly, the final group holds the remainder.
Non-destructive
The source array is not modified; you receive a new outer array of chunks.
Batching
Useful for UI pagination slices, queue workers, and CSV row batches.
Predictable length
Outer length is Math.ceil(array.length / size) for positive size.
Syntax
_.chunk(array, [size=1]) - array: the collection to split (array-like values are coerced).
- size: positive integer length for each chunk except possibly the last.
- Returns: a new array containing chunk arrays.
Even split
When the length is a multiple of size, every inner array has the same length.
import chunk from "lodash/chunk";
const rows = chunk(["a", "b", "c", "d"], 2);
// [["a", "b"], ["c", "d"]] Last chunk shorter
Remainder elements stay together in the final chunk.
import chunk from "lodash/chunk";
const rows = chunk([1, 2, 3, 4, 5], 2);
// [[1, 2], [3, 4], [5]] Empty input
An empty source array produces an empty outer array.
import chunk from "lodash/chunk";
chunk([], 3);
// [] 📋 _.chunk vs manual loops
| Approach | Pros | Cons |
|---|---|---|
_.chunk | Short, tested, consistent across environments | Adds a dependency (or one more import) |
for loop with slice | No dependency | More boilerplate and easier to mishandle bounds |
Pitfalls to avoid
Zero or negative size
Lodash coerces size with toInteger and clamps; non-positive sizes are unsafe to rely on. Pick a positive chunk size you control.
Shared references
Chunking does not clone objects inside the array; every chunk still points at the same object instances.
Memory
Materializing all chunks at once duplicates structure in memory; for very large streams consider iterators or streaming APIs instead.
❓ FAQ
Summary
- Purpose:
_.chunk(array, size)groups elements into fixed-length batches. - Immutability: the original array is unchanged; you get a new nested array.
- Next: Lodash _.compact() or return to the array methods hub.
_.chunk always returns a new outer array; inner chunks reference the same element values as the source array (objects are not cloned).
6 people found this page helpful
