JS Split Array into Chunks
Dividing an array into smaller arrays of a specified size is called split an array into chunks in JS. This operation is useful when you need to process a large array in smaller portions. We can also use this operation when you want to display an array in a paginated manner.
Why do we need to split array into chunks?
There are several reasons for splitting an array into chunks in JavaScript:
- Efficient processing: If you have a large array and you need to perform some operation on it, splitting it into smaller chunks can make the processing more efficient. Because processing a smaller chunk of data is usually faster than processing the entire array at once.
- Better memory management: It can also help with memory management. If you are working with a very large array, processing it all at once could lead to memory issues.
- Pagination: Splitting an array into chunks can also be useful for displaying data in a paginated format on a web page. For example, if you have a list of items that you want to display on a page, you could split the array into chunks of a certain size and display one chunk at a time.
Several ways to split array into chunks
These are the easy ways to split array into chunks:
1. Using a loop
function chunkArray(arr, chunkSize) {
const result = [];
for (let i = 0; i < arr.length; i += chunkSize) {
result.push(arr.slice(i, i + chunkSize));
}
return result;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArr = chunkArray(arr, 3);
//Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
In this code:
- We define a function chunkArray with two parameters: ‘arr’ for array to be chunked and ‘chunkSize’ for size of each chunk.
- Then we initiliazed an empty array ‘result’ to store the chunks
- Create loop through the array ‘arr’ using a for loop, starting at the beginning (i = 0) and incrementing by ‘chunkSize’ each time (i += chunkSize).
- Once the loop has finished, we return the result array, which contains all the chunks.
- Finally, we test the function by calling it with an example array ‘arr’ and chunk size 3, which should return the expected result of [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]].
2. Using Array.from
function chunkArray(arr, chunkSize) {
return Array.from({ length: Math.ceil(arr.length / chunkSize) }, (_, i) =>
arr.slice(i * chunkSize, i * chunkSize + chunkSize)
);
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArr = chunkArray(arr, 3);
//Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
In this code:
- In this method, we use the ‘Math.ceil’ function to calculate the number of chunks needed to split the array ‘arr’ into chunks of size ‘chunkSize’
- Then use the ‘Array.from’ method to create a new array with length equal to the number of chunks calculated in step 2.
- In the mapping function, we use the index of each element (i) to calculate the start and end indices of the chunk in the original array, using the same logic as in example