Approach 4 Using for-of loop
The for…of loop iterates over the iterable objects (like Array, Map, Set, arguments object, …,etc), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
Syntax:
for ( variable of iterableObjectName) { ... }
Example: In this example, the for loop iterates over the array of elements and prints the occurrences of all the elements in the console.
Javascript
const arr = [1, 2, 3, 2, 3, 4, 5, 5, 6, 1, 1, 4, 5, 7, 8, 8]; const count = {}; for (let ele of arr) { if (count[ele]) { count[ele] += 1; } else { count[ele] = 1; } } console.log(count); |
Output:
{ '1': 3, '2': 2, '3': 2, '4': 2, '5': 3, '6': 1, '7': 1, '8': 2 }
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: