📚
Count Elements
Count Elements - Explanation
쉬움 배열 O(n) O(n)
Problem Summary
Write a function that counts how many times a value appears in an array.
Go to Problem →Detailed Explanation
이 문제는 **filter와 length를 조합**하여 특정 값의 출현 횟수를 세는 방법을 학습합니다. **filter로 카운팅하기** filter로 조건에 맞는 요소만 추출한 후 length로 개수를 셉니다. **[1, 2, 1, 3, 1]에서 1 세기** 1. filter(x => x === 1) → [1, 1, 1] 2. [1, 1, 1].length → 3 **reduce로 구현 (대안)** ```javascript arr.reduce((count, x) => x === value ? count + 1 : count, 0); ``` **없는 값을 찾는 경우** filter 결과가 빈 배열이면 length는 0입니다.
Solution Code
solution.js
function count(arr, value) {
return arr.filter(x => x === value).length;
}Key Concepts from This Problem
1. filter 메서드
2. 배열 길이
3. 요소 카운팅
4. reduce 대안
Common Mistakes
✗ === 대신 ==를 사용하면 타입 변환이 발생합니다
✗ filter는 새 배열을 만들므로 메모리를 사용합니다
✗ 대용량 데이터에서는 reduce가 더 효율적입니다
Hints
Hint 1: filter를 사용하세요.
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(n)
Uses memory proportional to input size
Related Tags
#배열 #filter #카운팅