Categories
JavaScript Answers

How to count the number of times a same value appears in a JavaScript array?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *