split array into chunks code example

Example 1: react split array into chunks

const chunkSize = 10;
const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
const groups = arr.map((e, i) => { 
     return i % chunkSize === 0 ? arr.slice(i, i + chunkSize) : null; 
}).filter(e => { return e; });
console.log({arr, groups})

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); //split into chunks of two

Example 3: array chunk javascript

//#Source https://bit.ly/2neWfJ2 
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
console.log(chunk([1, 2, 3, 4, 5], 2));

Example 4: 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));