const chunk = (arr, size) => arr.reduce((acc, e, i) => (i % size ? acc[acc.length - 1].push(e) : acc.push([e]), acc), []);
// Examples
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3); // [[1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 4); // [[1, 2, 3, 4], [5, 6, 7, 8]]
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));
const splitArray=(arr, chunk)=>{
const elementInEachSubArray = Math.floor(arr.length / chunk)
const remainingElement = arr.length - (elementInEachSubArray * chunk)
let splitArray = Array.from({length: chunk}, ()=>[])
splitArray = splitArray.map(
(array, i)=>{
return arr.slice(i*elementInEachSubArray, elementInEachSubArray * (i + 1))
}
).map((array, i)=>[...array, arr[arr.length - remainingElement + i]].filter(Boolean))
console.log(splitArray)
}