JavaScript: How to find the count of an element in an array using filter( )

Let’s say we have an array of numbers in JavaScript that looks like this:

let array = [1, 2, 3, 5, 2, 8, 9, 2];

and we want to count the number of 2’s in the array.  A quick and direct way to get the count of 2’s would be to do something like this:

console.log(array.filter(x => x === 2).length);

which yields 3. A better way to do this is probably to set up a function that will return the count. For example:

function returnCount(arrayToCheck, element){
  let array = arrayToCheck;
  let elementToFind = element;
  let numberFound = array.filter(x => x === elementToFind).length;
  return numberFound;

Then call this function to get the result:

console.log(returnCount(array, 2));

which yields:


Here is what says about the JavaScript filter method:

The filter() method creates an array filled with all array elements that pass a test (provided as a function).

filter() does not execute the function for array elements without values.

filter() does not change the original array.

For more information about the JavaScript filter() method, see: