HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Split array into chunks

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayintosplitchunks

Problem

Let's say that I have an Javascript array looking as following:

["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.


What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?

Solution

The array.slice() method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    // do whatever
}


The last chunk may be smaller than chunkSize. For example when given an array of 12 elements the first chunk will have 10 elements, the second chunk only has 2.

Note that a chunkSize of 0 will cause an infinite loop.

Code Snippets

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    // do whatever
}

Context

Stack Overflow Q#8495687, score: 1399

Revisions (0)

No revisions yet.