LeetCode/js/chunk-array.js

25 lines
450 B
JavaScript
Raw Normal View History

/**
* @param {Array} arr
* @param {number} size
* @return {Array[]}
*/
var chunk = function(arr, size) {
let chunked = [];
let current = new Array();
for (let i = 0; i < arr.length; ++i) {
current.push(arr[i]);
if ((i + 1) % size == 0) {
chunked.push(current);
current = new Array();
}
}
if (current.length > 0) {
chunked.push(current);
}
return chunked;
};