Looping through and getting frequency of all the elements in an array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we will be given an array of numbers / strings that contains some duplicate entries, all we have to do is to return the frequency of each element in the array. Returning an object with element as key and it’s value as frequency would be perfect for this situation.

We will iterate over the array with a forEach() loop and keep increasing the count of elements in the object if it already exists otherwise we will create a new property for that element in the object.

And lastly, we will return the object.

The full code for this problem will be −

Example

const arr = [2,5,7,8,5,3,5,7,8,5,3,4,2,4,2,1,6,8,6];
const getFrequency = (array) => {
   const map = {};
   array.forEach(item => {
      if(map[item]){
         map[item]++;
      }else{
         map[item] = 1;
      }
   });
   return map;
};
console.log(getFrequency(arr));

Output

The output in the console will be −

{ '1': 1, '2': 3, '3': 2, '4': 2, '5': 4, '6': 2, '7': 2, '8': 3 }
raja
Published on 19-Aug-2020 06:52:14
Advertisements