Approach 3 Using reduce() method
The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
Example: In this example, the reduce() method is used to count the frequency of the elements of the array. We are printing the frequency of “1” in the array in the console.
Javascript
const arr = [1, 2, 3, 2, 3, 4, 5, 5, 6, 1, 1, 4, 5, 7, 8, 8]; function count(arr, element) { return arr.reduce((ele, arrayEle) => (arrayEle == element ? ele + 1 : ele), 0); }; console.log(count(arr, 1)); |
Output:
3
Count Frequency of an Array Item in JavaScript
In this article, we will be counting the frequency of an array item in Javascript.
When working with arrays there are situations when we need to count the frequency of an array item. Javascript provides us with some methods to count the occurrences of an item in an array, some of them are explained below: