Skip to content

Commit c142acb

Browse files
authored
code added
1 parent 50e96de commit c142acb

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

21_chunkArray.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Question Link: https://leetcode.com/problems/chunk-array/description/?envType=study-plan-v2&envId=30-days-of-javascript
2+
// Solution Link: https://leetcode.com/problems/chunk-array/solutions/5446329/javascript-easy-solution/
3+
4+
/*
5+
2677. Chunk Array
6+
7+
Given an array arr and a chunk size size, return a chunked array.
8+
A chunked array contains the original elements in arr, but consists of subarrays each of length size. The length of the last subarray may be less than size if arr.length is not evenly divisible by size.
9+
10+
You may assume the array is the output of JSON.parse. In other words, it is valid JSON.
11+
Please solve it without using lodash's _.chunk function.
12+
13+
Example 1:
14+
Input: arr = [1,2,3,4,5], size = 1
15+
Output: [[1],[2],[3],[4],[5]]
16+
Explanation: The arr has been split into subarrays each with 1 element.
17+
18+
Example 2:
19+
Input: arr = [1,9,6,3,2], size = 3
20+
Output: [[1,9,6],[3,2]]
21+
Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.
22+
23+
Example 3:
24+
Input: arr = [8,5,3,2,6], size = 6
25+
Output: [[8,5,3,2,6]]
26+
Explanation: Size is greater than arr.length thus all elements are in the first subarray.
27+
28+
Example 4:
29+
Input: arr = [], size = 1
30+
Output: []
31+
Explanation: There are no elements to be chunked so an empty array is returned.
32+
33+
Constraints:
34+
arr is a valid JSON array
35+
2 <= JSON.stringify(arr).length <= 10^5
36+
1 <= size <= arr.length + 1
37+
*/
38+
39+
40+
41+
/**
42+
* @param {Array} arr
43+
* @param {number} size
44+
* @return {Array}
45+
*/
46+
var chunk = function(arr, size) {
47+
let ans = [] ;
48+
49+
while (arr.length > 0){
50+
ans.push(arr.splice(0,size));
51+
}
52+
53+
return ans;
54+
};

0 commit comments

Comments
 (0)