chunk an array
Chunk an Array
Chunking an array means splitting it into smaller arrays with a specific size. For example, if we have an array of 10 elements and we want to chunk it into arrays of 3 elements each, we would end up with 4 smaller arrays: [0, 1, 2], [3, 4, 5], [6, 7, 8], and [9].
Method 1: Using a for loop
We can use a for loop and the slice
method to create chunks of the array:
function chunkArray(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArray = chunkArray(myArray, 3);
console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
In this example, we start by creating an empty array called chunks
that we will eventually fill with the smaller arrays. We then loop through the original array and increment the loop counter by the chunk size. For each iteration of the loop, we use the slice
method to extract a portion of the original array and add it to the chunks
array with the push
method.
Method 2: Using the splice method
Another way to chunk an array is to use the splice
method:
function chunkArray(arr, size) {
const chunks = [];
while (arr.length > 0) {
chunks.push(arr.splice(0, size));
}
return chunks;
}
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArray = chunkArray(myArray, 3);
console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
In this example, we again start by creating an empty array called chunks
. We then use a while
loop to repeatedly extract portions of the original array using the splice
method until the original array has been fully emptied. For each iteration of the loop, we add the extracted portion to the chunks
array with the push
method.
Both of these methods are effective for chunking an array, but you may want to choose one over the other depending on the specific use case and performance requirements.