-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
22 lines (19 loc) · 726 Bytes
/
index.js
File metadata and controls
22 lines (19 loc) · 726 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// --- Directions
// Given an array and chunk size, divide the array into many subarrays
// where each subarray is of length size
// --- Examples
// arrayChunk([1, 2, 3, 4], 2) --> [[1, 2], [3, 4]]
// arrayChunk([1, 2, 3, 4, 5], 2) --> [[1, 2], [3, 4], [5]]
// arrayChunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[1, 2, 3], [4, 5, 6], [7, 8]]
// arrayChunk([1, 2, 3, 4, 5], 4) --> [[1, 2, 3, 4], [5]]
// arrayChunk([1, 2, 3, 4, 5], 10) --> [[1, 2, 3, 4, 5]]
function arrayChunk(array, size) {
let result = [];
let resultLen = Math.ceil(array.length / size);
for (let i = 0; i < resultLen; i++) {
let index = i * size;
result.push(array.slice(index, size + index))
}
return result;
}
module.exports = arrayChunk;