Split array into chunks
Categories:
Efficiently Splitting Arrays into Chunks in JavaScript
Learn various techniques to divide a JavaScript array into smaller, manageable chunks, enhancing readability and performance for specific use cases.
Splitting an array into smaller chunks is a common task in JavaScript development. Whether you're paginating data, processing items in batches, or simply organizing your data structure, knowing how to effectively divide an array is a valuable skill. This article will explore several methods, from basic loop implementations to more modern approaches using array methods, highlighting their use cases and performance characteristics.
Method 1: Using a Simple For Loop
The most straightforward way to split an array is by iterating through it with a for
loop and using slice()
to extract chunks. This method provides explicit control over the chunking logic and is easy to understand, making it a good starting point for beginners.
function chunkArrayForLoop(arr, chunkSize) {
const result = [];
for (let i = 0; i < arr.length; i += chunkSize) {
result.push(arr.slice(i, i + chunkSize));
}
return result;
}
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArray = chunkArrayForLoop(myArray, 3);
console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
A basic for
loop implementation to chunk an array.
Method 2: Leveraging Array.prototype.reduce()
For a more functional programming approach, Array.prototype.reduce()
can be used to accumulate chunks. This method is concise and elegant, particularly for those familiar with functional patterns. It iterates over the array and builds up the new chunked array by pushing elements into new or existing sub-arrays.
function chunkArrayReduce(arr, chunkSize) {
return arr.reduce((acc, item, index) => {
const chunkIndex = Math.floor(index / chunkSize);
if (!acc[chunkIndex]) {
acc[chunkIndex] = []; // Start a new chunk
}
acc[chunkIndex].push(item);
return acc;
}, []);
}
const myArray = ['a', 'b', 'c', 'd', 'e', 'f'];
const chunkedArray = chunkArrayReduce(myArray, 2);
console.log(chunkedArray); // [['a', 'b'], ['c', 'd'], ['e', 'f']]
Chunking an array using the reduce()
method.
reduce()
offers a concise solution, it might be less intuitive for developers unfamiliar with functional programming concepts. Ensure your team understands this pattern before adopting it widely.Method 3: Using a Generator Function (ES6+)
Generator functions provide an elegant way to create iterators, and they can be particularly useful for chunking arrays, especially when dealing with very large arrays where you might not want to create all chunks in memory at once. This approach generates chunks on demand.
function* chunkArrayGenerator(arr, chunkSize) {
for (let i = 0; i < arr.length; i += chunkSize) {
yield arr.slice(i, i + chunkSize);
}
}
const myArray = [10, 20, 30, 40, 50, 60, 70];
const chunkIterator = chunkArrayGenerator(myArray, 3);
console.log(chunkIterator.next().value); // [10, 20, 30]
console.log(chunkIterator.next().value); // [40, 50, 60]
console.log(chunkIterator.next().value); // [70]
// To get all chunks as an array:
const allChunks = [...chunkArrayGenerator(myArray, 2)];
console.log(allChunks); // [[10, 20], [30, 40], [50, 60], [70]]
Using a generator function to create an iterable of array chunks.
Conceptual flow of array chunking