JavaScript(JS) JS split array into smaller chunks
To split an array into smaller chunks in JavaScript/JS, you can use a combination of the slice()
method and a loop. Here's an example:
const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const chunkSize = 3; const chunkedArray = []; for (let i = 0; i < myArray.length; i += chunkSize) { const chunk = myArray.slice(i, i + chunkSize); chunkedArray.push(chunk); } console.log(chunkedArray);
In this example, we have an array called myArray
and we want to split it into chunks of size 3. We create an empty array called chunkedArray
to hold our chunked subarrays.
We then use a for
loop to iterate over myArray
. The loop starts at i = 0
, and increments by chunkSize
with each iteration. For each iteration of the loop, we use the slice()
method to extract a chunk of the original array starting at index i
and ending at index i + chunkSize
. This creates a new subarray that contains chunkSize
elements.
We then push this subarray into chunkedArray
using the push()
method. Once the loop has finished, chunkedArray
contains an array of subarrays, each with chunkSize
elements (except for the last subarray, which may have fewer elements if the original array length is not evenly divisible by chunkSize
).
We log the chunkedArray
to the console using console.log(chunkedArray)
.