Given an array arr and a chunk size size, return a chunked array. 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.
You may assume the array is the output of JSON.parse. In other words, it is valid JSON.
Please solve it without using lodash's _.chunk function.
Example 1:
Input: arr = [1,2,3,4,5], size = 1
Output: [[1],[2],[3],[4],[5]]
Explanation: The arr has been split into subarrays each with 1 element.
Example 2:
Input: arr = [1,9,6,3,2], size = 3
Output: [[1,9,6],[3,2]]
Explanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.
Example 3:
Input: arr = [8,5,3,2,6], size = 6
Output: [[8,5,3,2,6]]
Explanation: Size is greater than arr.length thus all elements are in the first subarray.
Example 4:
Input: arr = [], size = 1
Output: []
Explanation: There are no elements to be chunked so an empty array is returned.
나의 풀이
/**
* @param {Array} arr
* @param {number} size
* @return {Array}
*/
var chunk = function(arr, size) {
const chunkArr = [];
let index = 0;
while(index < arr.length){
chunkArr.push(arr.slice(index, index + size));
index +=size;
}
return chunkArr;
};
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
[프로그래머스] 기능개발 (1) | 2024.03.15 |
---|---|
[프로그래머스] 2019 카카오 개발자 겨울 인턴십 튜플 (0) | 2024.03.09 |
이메일 인증번호 구현 With Next.Js & nodeMailer (0) | 2024.01.30 |
[프로그래머스] 괄호 회전하기 (1) | 2024.01.20 |
[프로그래머스] 귤 고르기 (0) | 2024.01.14 |