Chunk Array
Chunk Array - Explanation
Problem Summary
Write a function that splits an array into chunks of a specified size.
Go to Problem →Detailed Explanation
이 문제는 **배열을 일정 크기로 분할**하는 패턴을 학습합니다. 페이지네이션, 배치 처리 등에 유용합니다. **핵심 전략: slice로 부분 배열 추출** slice(start, end)는 start부터 end 직전까지의 요소를 새 배열로 반환합니다. **알고리즘 동작** 1. i를 size만큼 증가시키며 반복 2. 각 반복에서 slice(i, i + size)로 청크 추출 3. 결과 배열에 추가 **[1, 2, 3, 4, 5], size=2 처리 과정** - i=0: slice(0, 2) → [1, 2] - i=2: slice(2, 4) → [3, 4] - i=4: slice(4, 6) → [5] (범위를 벗어나도 있는 요소만 반환) **slice의 특성** - 범위가 배열 길이를 초과해도 에러 없이 가능한 요소만 반환 - 원본 배열을 변경하지 않음 **마지막 청크 처리** 배열 길이가 size로 나누어 떨어지지 않으면 마지막 청크는 더 작을 수 있습니다. slice가 자동으로 처리합니다. **실용적 활용** - 페이지네이션: 한 페이지에 표시할 아이템 분리 - 배치 처리: 대량 데이터를 작은 단위로 처리 - 그리드 레이아웃: 행별로 아이템 그룹화
Solution Code
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(n)
Uses memory proportional to input size