This blog will demonstrate the methods for counting specific elements in an array in JavaScript.
How to Count Certain Elements in an Array in JavaScript?
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.
Syntax
Use the following syntax for using the filter() method:
Example
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.
Syntax
For using the reduce() method, utilize the given syntax:
Example
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.
Syntax
Follow the syntax to use the “for” loop:
Example
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)
count++;
}
Lastly, print the count on the console:
Output
We have compiled all the instructions relevant to counting the specific element in an array.
Conclusion
To count certain elements in an array in JavaScript, use the “filter()” method, “reduce()” method, or the traditional “for” loop. filter() method filters the elements that match the specified element, while the reduce() method or the for loop gives the total number of occurrences of the particular element. This blog demonstrated the methods for counting specific elements in an array in JavaScript.