-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchunky_monkey.js
More file actions
52 lines (46 loc) · 1.52 KB
/
chunky_monkey.js
File metadata and controls
52 lines (46 loc) · 1.52 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
// Chunky Monkey
// Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
// Tests:
// chunkArrayInGroups(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]].
// chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3) should return [[0, 1, 2], [3, 4, 5]].
// chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2) should return [[0, 1], [2, 3], [4, 5]].
// chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4) should return [[0, 1, 2, 3], [4, 5]].
// chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3) should return [[0, 1, 2], [3, 4, 5], [6]].
// chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].
function chunkArrayInGroups(arr, size) {
var answer = [];
var i = 0;
while ( i < arr.length ) {
answer.push(arr.slice(i, i + size));
i += size;
}
return answer;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
// Possible answers from the FCC Wiki:
//
// Solution 2:
//
// function chunkArrayInGroups(arr, size) {
// // Break it up
// // It's already broken :(
// arr = arr.slice();
// var arr2 = [];
// for(var i = 0, len = arr.length; i < len; i+=size) {
// arr2.push(arr.slice(0, size));
// arr = arr.slice(size);
// }
// return arr2;
// }
//
// Solution 4:
//
// // splice & slice, avoiding size counting
// function chunkArrayInGroups(arr, size) {
// var ar = arr.slice();
// var res = [];
// do {
// res.push(ar.splice(0, size));
// } while (ar.length > 0);
// return res;
// }