ice.fo.utils
Version:
29 lines (24 loc) • 759 B
JavaScript
/* eslint-disable vue/max-len */
/**
* Creates an array of elements split into groups with length size. If array can't be split evenly, the final chunk will be the remaining elements.
*
* @example
* splitIntoChunks([1,2,3,4], 2); // returns [ [1,2], [3,4] ]
* splitIntoChunks([1,2,3,4], 3); // returns [ [1,2,3], [4] ]
* splitIntoChunks([1,2,3,4], 5); // returns [ [1,2,3,4] ]
*
* @param array
* @param length
* @returns {[]}
*/
export default function splitIntoChunks(array, length) {
if (array.length < length) {
return [array];
}
const result = [];
const chunkCount = Math.ceil(array.length / length);
for (let i = 0; i < chunkCount; i++) {
result.push(array.slice(i * length, i * length + length));
}
return result;
}