Array Sum
Array Sum - Explanation
Problem Summary
Write a function that returns the sum of all numbers in an array.
Go to Problem →Detailed Explanation
이 문제는 배열의 모든 요소를 순회하며 합계를 구하는 방법을 학습합니다. **reduce 메서드**는 배열을 하나의 값으로 축소하는 데 가장 적합한 도구입니다. **reduce 메서드의 동작 원리** `reduce((accumulator, currentValue) => ..., initialValue)` - accumulator(acc): 누적된 결과값 - currentValue(cur): 현재 처리 중인 요소 - initialValue: 초기값 (여기서는 0) 배열 [1, 2, 3, 4, 5]의 경우: 1. acc=0, cur=1 → 0+1=1 2. acc=1, cur=2 → 1+2=3 3. acc=3, cur=3 → 3+3=6 4. acc=6, cur=4 → 6+4=10 5. acc=10, cur=5 → 10+5=15 **초기값의 중요성** 초기값 0을 제공하면 빈 배열에서도 에러 없이 0을 반환합니다. 초기값이 없으면 빈 배열에서 에러가 발생합니다. **for문으로 구현하기** reduce가 어렵다면 for문으로도 같은 결과를 얻을 수 있습니다: `let total = 0; for (const num of arr) total += num;`
Solution Code
function sum(arr) {
return arr.reduce((acc, cur) => acc + cur, 0);
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(1)
Uses almost no additional memory