Method 1: Slice() for Dividing an Array Into Chunks
To demonstrate this, first, create an array of integers with the following line of code:
Then, define the size of each chunk that is to be derived from the original array:
Afterwards, simply use the for loop to iterate through the array and create an array variable chunk with the help of slice() method with the following lines of code:
let chunk;
chunk = my_array.slice(i, i + chunkSize);
console.log(chunk);
}
In this code snippet:
- for loop is used to iterate through the original array, and for every iteration, the value of the iterator variable (i) is increased by the chunk size to avoid rereading the same chunk.
- Inside the for loop, a new array variable is created named chunk
- my_array.slice() cuts a chunk from the array based on the arguments and stores that in the chunk variable
- At the end, the console log function prints out the chunk onto the terminal.
The complete code snippet is as:
chunkSize = 2;
for (i = 0; i < my_array.length; i += chunkSize) {
let chunk;
chunk = my_array.slice(i, i + chunkSize);
console.log(chunk);
}
Upon execution, the above code snippet produces the following results:
The output displays the array converted into smaller chunks each of size 2.
Method 2: Using Splice() for Dividing an Array Into Smaller Chunks
To showcase the use of the splice() method, first create a new array with the following lines of code:
Define the size of chunk just like in the first method using the following line:
Afterwards, a while() loop is used in combination with splice() to iterate through the array:
let chunk;
chunk = my_array.splice(0, chunkSize);
console.log(chunk);
}
In this code snippet:
- A while loop is used to iterate through the array with the condition that while the array length is greater than 0 because using splice() reduces the original array’s size.
- Inside the while loop, a chunk variable is created to store each chunk.
- Then, the chunk variable is set equal to my_array.splice() method, which returns the chunk from the array starting from the 0th index to the index decided by the chunkSize
- Lastly, print out the chunk on the terminal using the console log function
The complete code snippet is as:
chunkSize = 4;
while (my_array.length > 0) {
let chunk;
chunk = my_array.splice(0, chunkSize);
console.log(chunk);
}
Executing this code gives the following output:
It is clear from the output that the splice() method splits the array into chunks each of size 4.
Conclusion
In JavaScript, the programmer can use two methods to split or divide an array into smaller yet equal chunks. These methods include using the slice() method and the splice() method in combination with for loop and while loop. This article has displayed the working of both methods with the help of two examples.