array divide javascript code example
Example 1: javascript array split chunk
const chunk = (arr, size) => arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3);
chunk([1, 2, 3, 4, 5, 6, 7, 8], 4);
Example 2: 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);