Looking for an easy snippet to split the array in javascript? The most common case where I need it is when building the grids in vue.js, I often require splitting the array so that I can create a row according to that.
/**
* Returns an array with arrays of the given size.
*
* @param myArray {Array} Array to split
* @param chunkSize {Integer} Size of every group
*/functionchunkArray(myArray, chunk_size) {
let results = [];
while (myArray.length) {
results.push(myArray.splice(0, chunk_size))
}
return results;
}
// Usage// Split in group of 3 itemsvar result = chunkArray([1,2,3,4,5,6,7,8], 3)
// Outputs : [ [1,2,3] , [4,5,6] ,[7,8] ]console.log(result)