๐Ÿ“š

Count Elements

Count Elements
์‰ฌ์›€ ๋ฐฐ์—ด +10pts

Problem

Write a function that counts how many times a value appears in an array.

Examples

Input: count([1, 2, 1, 3, 1], 1)
Output: 3

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, ...

View detailed explanation โ†’

Key Concepts

filter ๋ฉ”์„œ๋“œ ๋ฐฐ์—ด ๊ธธ์ด ์š”์†Œ ์นด์šดํŒ… reduce ๋Œ€์•ˆ
Time: O(n) Space: O(n)
solution.js
Ctrl + Enter
Run tests to see results here.