To count the number of times a same value appears in a JavaScript array, we call the filter
method.
For instance, we write
const getOccurrence = (array, value) => {
return array.filter((v) => v === value).length;
};
console.log(getOccurrence(arr, 1));
to call array.filter
with a callback that checks if v
in array
equals to value
.
An array of values in array
that equals to value
is returned.
Then we get the count using the length
property.