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
Splitting an array into chunks in JavaScript
In JavaScript, splitting an array into smaller chunks of equal size is a common operation. This article covers multiple approaches to divide array elements into n-sized chunks effectively.
Input and Output Example:
Consider an array with elements [10, 20, 30, 40] and chunk size of 2:
Input = [10, 20, 30, 40] Output = [[10, 20], [30, 40]]
The array gets divided into chunks where each sub-array contains the specified number of elements.
Using slice() Method with for Loop
The slice() method creates a shallow copy of a portion of an array without modifying the original array. It's ideal for chunking because it preserves the original data.
Syntax
array.slice(start, end)
Returns elements from start index up to (but not including) end index.
Example
function arrayIntoChunks(array, chunkSize) {
const result = [];
for (let i = 0; i
[ [ 1, 6 ], [ 7, 3 ], [ 5, 9 ], [ 4 ] ]
Original array: [ 1, 6, 7, 3, 5, 9, 4 ]
Using splice() Method with while Loop
The splice() method removes elements from the original array and returns them. This approach modifies the original array during the chunking process.
Example
function arrayIntoChunks(array, chunkSize) {
const result = [];
while (array.length > 0) {
const chunk = array.splice(0, chunkSize);
result.push(chunk);
}
return result;
}
const array = [1, 6, 7, 3, 5, 9, 4];
console.log(arrayIntoChunks(array, 2));
console.log("Original array after chunking:", array); // Empty
[ [ 1, 6 ], [ 7, 3 ], [ 5, 9 ], [ 4 ] ]
Original array after chunking: []
Using Array Prototype Extension
This approach extends the Array prototype to add a custom chunk() method, making it available on all arrays.
Object.defineProperty(Array.prototype, 'chunk', {
value: function(chunkSize) {
const result = [];
for (let i = 0; i
[ [ 10, 20, 30 ], [ 40, 50, 60 ], [ 70, 80 ] ]
Comparison
| Method | Modifies Original? | Performance | Use Case |
|---|---|---|---|
slice() |
No | Good | When original array must be preserved |
splice() |
Yes | Good | When original array can be consumed |
| Prototype extension | No | Good | For reusable chunk functionality |
Key Points
slice()preserves the original array, making it safer for most use casessplice()modifies the original array, which can be memory-efficient for large arraysPrototype extension provides convenient syntax but should be used carefully in shared codebases
Conclusion
The slice() method with a for loop is the most commonly used approach for array chunking as it preserves the original data. Choose splice() when memory optimization is needed and the original array can be modified.
