 
 Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }Advertisements
                    