split list into chunks javascript code example
Example 1: javascript split array into chuncks of
function splitArrayIntoChunksOfLen(arr, len) {
var chunks = [], i = 0, n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks;
}
var alphabet=['a','b','c','d','e','f'];
var alphabetPairs=splitArrayIntoChunksOfLen(alphabet,2);
Example 2: array chunk javascript
let input = [1,2,3,4,5,6,7,8,9];
let chunked = []
let size = 2;
for (let i = 0; i < input.length; i += size) {
chunked.push(input.slice(i, i + size))
}
console.log(chunked)
Example 3: split array into chunks javascript
Array.prototype.chunk = function(size) {
let result = [];
while(this.length) {
result.push(this.splice(0, size));
}
return result;
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(arr.chunk(2));