What is the _.chunk() method in Lodash?

Overview

The _.chunk() method in Lodash is used to reduce an array into multiple chunks, where each chunk is also an array of a specified size.

Syntax

_.chunk(array, size)

Parameters

This method accepts the following parameters:

  • array: This is the array to be reduced.
  • size: This is the size of the chunk.

Return value

This method returns an array of chunks.

Example

Let’s look at an example of the _.chunk() method in the code snippet below:

Console

Explanation

In the HTML tab:

  • Line 5: We import the lodash script.

In the JavaScript tab:

  • Line 2: We create an array and initialize it with a few values.
  • Line 5: We create a variable size and initialize it with 2.
  • Lines 8: We use the _.chunk() method to reduce the array into small chunks.
  • Lines 11: We print the output on the console.

Output

  • In the output, we see an array of chunks.
  • The first two chunks contain 2 elements respectively, and the last chunk contains the remaining elements of the array.

Free Resources