Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Chunking arrays in JavaScript
Chunking arrays in JavaScript means splitting a single array into smaller subarrays of a specified size. This is useful for pagination, data processing, and organizing information into manageable groups.
For example, if we have an array of 7 elements and want chunks of size 2, the last chunk will contain only 1 element since 7 is not evenly divisible by 2.
Input and Expected Output
Given this input array:
const arr = [1, 2, 3, 4, 5, 6, 7];
The expected output should be:
[[1, 2], [3, 4], [5, 6], [7]]
Using a For Loop Approach
This method iterates through the array and builds chunks by checking if the current chunk is full:
const arr = [1, 2, 3, 4, 5, 6, 7];
const chunk = arr => {
const size = 2;
const chunkedArray = [];
for (let i = 0; i
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]
Using Array.slice() Method
A more concise approach using slice() to extract chunks directly:
const arr = [1, 2, 3, 4, 5, 6, 7];
const chunkArray = (array, size) => {
const result = [];
for (let i = 0; i
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
Comparison
| Method | Readability | Performance | Flexibility |
|---|---|---|---|
| For Loop | Moderate | Good | Limited to size 2 |
| Array.slice() | High | Good | Any chunk size |
How It Works
The for loop approach checks if the last subarray is full (length equals size) or doesn't exist. If so, it creates a new subarray. Otherwise, it adds the element to the existing subarray.
The slice approach increments the loop counter by the chunk size and extracts portions of the original array using slice().
Conclusion
Array chunking is essential for data pagination and processing. The slice() method provides a cleaner, more flexible solution compared to manual loop-based approaches.
