Getting the frequency of an element in an array in JavaScript

Getting the frequency of an element in an array in JavaScript

First of all, what is frequency? According to Wikipedia, it's" the rate at which something occurs over a particular period of time or in a given sample." There are multiple ways to get the frequency of an element in an array. In this article, we'll focus on one of those ways by using some of the higher-order functions in Javascript.

Let's begin

For instance, if we have an array of letters:

const letters = ["a", "b", "c", "a", "b", "c", "a", "b"];

To get the frequency of each element, we will first need to create an empty object named count:

const count = {};

Next, we'll utilize one those higher order functions we were talking about:

letters.forEach(e => count[e] ? count[e]++ : count[e] = 1 );

What the above code does is simply check, if each element of letters is present in count. Initially count is empty and does not contain any of letters elements, so when the ternary operator runs on an element of letters to check if its present in count for the first time, it's going to work with the falsy condition which is to assign letters elements to 1 in the count object. So the count object will then become:

console.log(count) // {"a" : 1, "b" : 1, "c" : 1};

Afterward, when the ternary operator checks if count has an element of letters that has already been checked, the ternary operator will then run the truthy condition which is to increment the value of the elements in letters if they are already present in count, so count will now become:

console.log(count) // {"a" : 3, "b" : , "c" : 2};

And just like that ladies and gentlemen, we've been able to get the frequency of each element of letters.

Conclusion

Here's the complete code:

const letters = ["a", "b", "c", "a", "b", "c", "a", "b"];
const count = {};
letters.forEach(e => count[e] ? count[e]++ : count[e] = 1 );

console.log(count) // {"a" : 1, "b" : 1, "c" : 1}

P.S: This code can be used for both strings and numbers.