Sometimes, we want to find the number of occurrences a given value has in an array with JavaScript.
In this article, we’ll look at how to find the number of occurrences a given value has in an array with JavaScript.
How to find the number of occurrences a given value has in an array with JavaScript?
To find the number of occurrences a given value has in an array with JavaScript, we use the array filter method.
For instance, we write
const dataset = [2, 2, 4, 2, 6, 4, 7, 8];
const search = 2;
const occurrences = dataset.filter((val) => {
return val === search;
}).length;
console.log(occurrences);
to call datset.filter with a callback that checks if val in dataset is the same as search and return an array where all the values are equal to search.
Then we get the length property to get the number of items equal to search.
Conclusion
To find the number of occurrences a given value has in an array with JavaScript, we use the array filter method.