How Lodash _.chunk Divides Arrays in JavaScript
The _.chunk method in the Lodash library is a utility
function designed to split a single array into smaller arrays, or
"chunks," of a designated length. This article covers the syntax of
_.chunk, explains the internal logic it uses to segment
elements, demonstrates how it handles uneven splits, and outlines common
edge cases.
Syntax and Parameters
The syntax for _.chunk is straightforward:
_.chunk(array, [size=1])array: The source array to be processed.size(optional): A positive integer specifying the maximum length of each chunk. If omitted, it defaults to1.
The method returns a new two-dimensional array containing the grouped elements without mutating the original array.
How _.chunk Works
Internally
The division mechanism works sequentially from index 0
to the end of the input array:
- Length Validation: The method checks the length of
the input array. If the array is empty or the
sizeparameter is less than1, it immediately returns an empty array[]. - Sequential Slicing: The function initializes an
empty results array and loops through the source array, advancing the
index by the specified
sizeon each iteration. - Sub-array Extraction: During each step, a segment
of the array—from the current index up to
index + size—is extracted using an operation equivalent toArray.prototype.slice. - Push to Result: Each extracted slice is pushed as an independent array into the parent array.
Handling Uneven Splits
If the total number of elements in the array is not evenly divisible
by size, _.chunk does not throw an error or
pad the missing spots. Instead, the final chunk will simply contain the
remaining elements, resulting in a length smaller than the specified
size.
const numbers = [1, 2, 3, 4, 5, 6, 7];
// Even division where possible, remainder at the end
const result = _.chunk(numbers, 3);
// Output: [[1, 2, 3], [4, 5, 6], [7]]Practical Examples
Default Behavior
When no size parameter is provided, _.chunk groups every
item into its own individual array:
const letters = ['a', 'b', 'c', 'd'];
console.log(_.chunk(letters));
// Output: [['a'], ['b'], ['c'], ['d']]Evenly Sized Groups
When the array length divides evenly by the chunk size, all sub-arrays have equal length:
const values = [10, 20, 30, 40];
console.log(_.chunk(values, 2));
// Output: [[10, 20], [30, 40]]Edge Cases
_.chunk safely handles out-of-bounds parameters and
unusual inputs:
- Size Exceeds Array Length: If the
sizeis greater than the array's total length, the function returns a single sub-array containing all original elements._.chunk([1, 2], 5); // Output: [[1, 2]] - Size Less Than One: Passing
0or negative values returns an empty array._.chunk([1, 2, 3], 0); // Output: [] - Empty or Nullish Input: Passing an empty array,
null, orundefinedsafely evaluates to[].