-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrayChunk.js
More file actions
40 lines (32 loc) · 968 Bytes
/
arrayChunk.js
File metadata and controls
40 lines (32 loc) · 968 Bytes
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
29
30
31
32
33
34
35
36
37
38
39
40
// --- Directions
// Given an array and chunk size, divide the array into many subarrays
// where each subarray is of length size
// --- Examples
// chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
// chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
// chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
// chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
// Solution No. 1
function arrayChunk(array, size) {
let chunked = [];
for(let element of array) {
let lastElement = chunked[chunked.length -1];
if(!lastElement || chunked.length === size) {
chunked.push([element]);
} else {
lastElement.push(element);
}
}
return chunked;
}
// Solution No. 2
function arrayChunk(array, size) {
let chunked = [];
let index = 0;
while(index < array.length) {
chunked.push(array.slice(index, index+size));
index += size;
}
return chunked
}