File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 2677. Chunk Array
2
+ // URL -> https://leetcode.com/problems/chunk-array/
3
+
4
+ /**
5
+ * @param {Array } arr
6
+ * @param {number } size
7
+ * @return {Array }
8
+ */
9
+ var chunk = function ( arr , size ) {
10
+ let result = [ ] ;
11
+
12
+ if ( arr . length === 0 ) return [ ] ;
13
+ let count = 0 ;
14
+
15
+ let chunk = [ ] ;
16
+ for ( let i = 0 ; i < arr . length ; i ++ ) {
17
+ chunk . push ( arr [ i ] ) ;
18
+ count ++ ;
19
+
20
+ if ( count === size ) {
21
+ result . push ( chunk ) ;
22
+ chunk = [ ] ;
23
+ count = 0 ;
24
+ }
25
+ }
26
+
27
+ if ( chunk . length ) result . push ( chunk )
28
+
29
+ return result ;
30
+ } ;
31
+
32
+ // Alternative Solution
33
+
34
+ // /**
35
+ // * @param {Array } arr
36
+ // * @param {number } size
37
+ // * @return {Array }
38
+ // */
39
+ // var chunk = function (arr, size) {
40
+ // if (arr.length < 1) return [];
41
+
42
+ // let res = [];
43
+ // for (let i = 0; i < arr.length; i++) {
44
+ // res.push(arr.slice(i, i + size));
45
+ // i = i + size - 1
46
+ // }
47
+
48
+ // return res;
49
+ // };
You can’t perform that action at this time.
0 commit comments