To find out how many times an array element appears with JavaScript, we use the filter
method.
For instance, we write
const countInArray = (array, what) => {
return array.filter((item) => item == what).length;
};
to define the countInArray
function.
In it, we get the count the number of items equal to what
by calling array.filter
with a callback that returns if item
equals to what
to return an array with entries with what
inside.
Then we get the length
property to get the count of what
in the array returned by filter
.
Top comments (0)