Sometimes, we want to count the number of times a same value appears in a JavaScript array.
In this article, we’ll look at how to count the number of times a same value appears in a JavaScript array.
How to count the number of times a same value appears in a JavaScript array?
To count the number of times a same value appears in a JavaScript array, we use the array filter method.
For instance, we write
const getOccurrence = (array, value) => {
return array.filter((v) => v === value).length;
};
const arr = [2, 3, 1, 3, 4, 5, 3, 1];
console.log(getOccurrence(arr, 1));
to define the getOccurrence function with the array and value as parameters.
And we return the number of times value appears in array by calling “array.filterwith a callback that returns the predicatevinarrayequalsvalueand then get the returned array'slength`.
Conclusion
To count the number of times a same value appears in a JavaScript array, we use the array filter method.