9
9
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
10
10
11
11
function chunk ( array , size ) {
12
+ let currentChunk = 0 ;
13
+ let result = [ ] ;
14
+ let chunk = [ ] ;
12
15
16
+ for ( var i = 0 ; i < array . length ; i ++ ) {
17
+ if ( currentChunk == size ) {
18
+ result . push ( chunk ) ;
19
+ currentChunk = 0 ;
20
+ chunk = [ ] ;
21
+ }
22
+
23
+ currentChunk ++ ;
24
+ chunk . push ( array [ i ] ) ;
25
+ }
26
+
27
+ if ( chunk . length ) result . push ( chunk ) ;
28
+
29
+ return result ;
30
+ }
31
+
32
+
33
+ function chunkSolution1 ( array , size ) {
34
+ // create empty array to hold all other arrays
35
+ const chunked = [ ] ;
36
+
37
+ for ( let element of array ) {
38
+ // retrieve the last element in the chunked array
39
+ const last = chunked [ chunked . length - 1 ] ;
40
+
41
+ // if there is no last element or it's length is the size
42
+ if ( ! last || last . length === size ) {
43
+
44
+ // add a new chunk with the current element
45
+ chunked . push ( [ element ] ) ;
46
+ } else {
47
+ // add the current element into the chunk
48
+ last . push ( element ) ;
49
+ }
50
+ }
51
+
52
+ return chunked ;
13
53
}
14
54
15
55
16
- console . log ( chunk ( [ 1 , 2 , 3 , 4 ] , 2 ) ) ;
56
+ // Rolling window with startIndex variable
57
+ // Good practice for using Array.prototype.slice
58
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
59
+ function chunkSolution2 ( array , size ) {
60
+ let startIndex = 0 ;
61
+ let output = [ ] ;
62
+
63
+ while ( startIndex < array . length ) {
64
+
65
+ output . push ( array . slice ( startIndex , startIndex + size ) ) ;
66
+
67
+ startIndex += size ;
68
+ }
69
+
70
+ return output ;
71
+ }
72
+
73
+
74
+
75
+ console . log ( chunkSolution2 ( [ 1 , 2 , 3 , 4 ] , 2 ) ) ;
76
+ console . log ( chunkSolution2 ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] , 3 ) ) ;
77
+ console . log ( chunkSolution2 ( [ 1 , 2 , 3 , 4 , 5 ] , 4 ) ) ;
0 commit comments