To count certain elements in an array, use the following methods:
- filter() method
- reduce() method
- for loop
Method 1: Count Certain Elements in an Array Using filter() Method
To count certain elements in an array, use the “filter()” method. This method iterates through each array element and filters out elements that meet the condition. It gives a new array that contains filtered elements depending on a condition.
Use the following syntax for using the filter() method:
Let’s create an array of numbers:
Store element in a variable “element” that will be searched in an array:
Invoke the filter() method and check the existence of the element in a callback function:
Now, print the resultant filtered array on the console:
The given output displays the array which filtered out the number “5” from an array:
Method 2: Count Certain Elements in an Array Using reduce() Method
filter() method gives an array of matched elements, not the exact count of the specified element. However, the “reduce()” method counts a certain element in an array. It is the most effective method to find the number of occurrences/instances of each element/value in an array. It takes a callback function that iterates through every element and finds the occurrence of the specified element.
For using the reduce() method, utilize the given syntax:
Call the reduce() method on an array and find the total occurrences of the element “5” in an array:
(value == 5 ? count + 1 : count), 0)
Finally, print the total count of the element “5” in an array using the “console.log()” method:
The output indicates that the total count of element “5” in an array is “4”:
Method 3: Count Certain Elements in an Array Using for Loop
You can also use the traditional “for” loop for counting the specific element in an array. It permits iterating through every element in an array and comparing it with the particular element that will be needed.
Follow the syntax to use the “for” loop:
Set count to 0:
Iterate the array until its length and compare elements with the particular element that is “5” to check the total number of occurrences in an array:
if(array[i] == element)
Lastly, print the count on the console:
We have compiled all the instructions relevant to counting the specific element in an array.