Building a frequency object from an array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals. The function should construct and return an object based on the array.

The keys of the object should be the unique elements of the array and their value the number of times they appear in the array.

Example

const arr = [4, 6, 3, 1, 5, 8, 9, 3, 4];
const findFrequency = (arr = []) => {
    const map = {};
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(map.hasOwnProperty(el)){
         map[el]++;
      }else{
         map[el] = 1;
      };
   };
   return map;
};
console.log(findFrequency(arr));

Output

And the output in the console will be −

{ '1': 1, '3': 2, '4': 2, '5': 1, '6': 1, '8': 1, '9': 1 }
raja
Published on 25-Nov-2020 08:11:08
Advertisements