Building frequency map of all the elements in an array JavaScript


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 an element as key and its 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 −

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));

The output in the console will be −

{ '1': 1, '2': 3, '3': 2, '4': 2, '5': 4, '6': 2, '7': 2, '8': 3 }

Updated on: 09-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements