-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchunk-array.js
28 lines (22 loc) · 883 Bytes
/
chunk-array.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Given an array arr and a chunk size size, return a chunked array. A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size.
// You may assume the array is the output of JSON.parse. In other words, it is valid JSON.
// Please solve it without using lodash's _.chunk function.
// Link: https://leetcode.com/problems/chunk-array/description/
//1st soln O(n)
var chunk = function(arr, size) {
let res = [];
let curr = [];
let cnt = 0;
for(let i = 0; i < arr.length; i++) {
curr.push(arr[i]);
cnt++;
if(cnt === size) {
res.push(curr);
cnt = 0;
curr = [];
} else if(i === arr.length -1) {
res.push(curr);
}
}
return res;
};