To count the occurrences / frequency of array elements with JavaScript, we use a for-of loop.
For instance, we write
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const counts = {};
for (const num of arr) {
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
to define the counts
object.
Then we use a for-of loop to loop through the arr
array and set counts[num]
to counts[num] + 1
if it’s already set and 1 otherwise.