乐闻世界logo
搜索文章和话题

How to partition array into multiple groups using Lodash?

1个答案

1

When you need to split an array into multiple chunks of equal size, you can use Lodash's _.chunk function. This is particularly useful for processing batched data or implementing pagination.

Example

Suppose we have an array containing numbers from 1 to 10:

javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

We want to split this array into multiple chunks of size 3. We can use the _.chunk function as follows:

javascript
import _ from 'lodash'; const result = _.chunk(numbers, 3); console.log(result);

The output will be:

shell
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Explanation

In this example, the first argument _.chunk(numbers, 3) is the array to split, and the second argument specifies the number of elements each chunk should contain. _.chunk traverses the array sequentially and splits it into chunks of the specified size. If the original array cannot be evenly divided, the last chunk will contain the remaining elements, as shown in the example [10].

This method is especially suitable for real-world scenarios such as displaying paginated data. We hope this example clearly demonstrates how to use Lodash's _.chunk to split arrays.

2024年8月9日 04:05 回复

你的答案