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])

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:

  1. Length Validation: The method checks the length of the input array. If the array is empty or the size parameter is less than 1, it immediately returns an empty array [].
  2. Sequential Slicing: The function initializes an empty results array and loops through the source array, advancing the index by the specified size on each iteration.
  3. 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 to Array.prototype.slice.
  4. 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: