JSFiddle - React, Tailwind, and code Playground
by rakhi5b4
JavaScript
var array = [1,2,3,4,5,6,7,8,9,10,11];
function splitUp(arr, n) {
var rest = arr.length % n,
restUsed = rest,
partLength = Math.floor(arr.length / n),
result = [];
for(var i = 0; i < arr.length; i += partLength) {
var end = partLength + i,
add = false;
if(rest !== 0 && restUsed) {
end++;
restUsed--;
add = true;
}
result.push(arr.slice(i, end));
if(add) {
i++;
}
}
return result;
}
console.log(JSON.stringify(splitUp(array, 2)));
console.log(JSON.stringify(splitUp(array, 3)));
console.log(JSON.stringify(splitUp(array, 4)));
console.log(JSON.stringify(splitUp(array, 5)));
Array.prototype.chunk = function ( n ) {
if ( !this.length ) {
return [];
}
return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};