Count How Many Times A Value Appears In An Array

Darren Jones
February 23, 2022

The following function accepts a value and array and will return the number of times that value appears in the array.

It works by using the Array.filter method to return an array that only contains the value we are counting, after that we just need to use the length method to count how many values there are.

Here’s how we could use it to find how many 7s there are in an array:

copy code
javascript
const count = (value,array) => array.filter(el => el === value).length

const numbers = [3,5,6,2,2,4,1,5,6,7,4,8,6,3,4,7,2,3]

// Count how many times 7 appears in 'numbers' array
count(7,numbers)
// Output: 2


Know a better answer? Join our our community and let us know.