To split an array into smaller chunks of a specified size in JavaScript, you can create a reusable function. Below is a common and efficient approach:
Chunk Array Function
function chunkArray(array, size) {
if (size <= 0) throw new Error("Chunk size must be greater than 0");
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
// Example usage
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunkArray(arr, 3);
console.log(chunked); // Output: [[1, 2, 3], [4, 5, 6], [7, 8]]
Explanation:
- The function takes two parameters:
array
: The array to split.size
: The size of each chunk.
- Inside the loop:
array.slice(i, i + size)
creates a subarray starting at indexi
and ending ati + size
(not inclusive).- Each chunk is pushed into the
result
array.
- The loop increments by the chunk size (
i += size
) to process the next chunk.
Alternative Using reduce()
You can also use the Array.reduce()
method to achieve the same result:
function chunkArray(array, size) {
if (size <= 0) throw new Error("Chunk size must be greater than 0");
return array.reduce((chunks, item, index) => {
const chunkIndex = Math.floor(index / size);
if (!chunks[chunkIndex]) {
chunks[chunkIndex] = []; // Start a new chunk
}
chunks[chunkIndex].push(item);
return chunks;
}, []);
}
// Example usage
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunkArray(arr, 3);
console.log(chunked); // Output: [[1, 2, 3], [4, 5, 6], [7, 8]]
Explanation:
reduce()
iterates over the array and groups elements into chunks.Math.floor(index / size)
determines the chunk index for the current item.- If the current chunk doesn’t exist, a new empty array is created.
- The current item is added to the appropriate chunk.
Using Modern Libraries (Optional)
If you’re using a library like Lodash, it has a built-in chunk
function:
Example with Lodash:
// Import lodash
const _ = require('lodash');
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = _.chunk(arr, 3);
console.log(chunked); // Output: [[1, 2, 3], [4, 5, 6], [7, 8]]
Lodash _.chunk
Method:
- Automatically handles edge cases.
- Requires importing Lodash.
Edge Cases to Consider
- Empty Array:
chunkArray([], 3); // Output: []
- Chunk Size Greater Than Array Length:
chunkArray([1, 2, 3], 5); // Output: [[1, 2, 3]]
- Negative or Zero Chunk Size:
chunkArray([1, 2, 3], 0); // Throws an error: "Chunk size must be greater than 0"
Both methods (using slice()
or reduce()
) are efficient and versatile. Choose the one that fits your coding style! Let me know if you’d like to explore further.