
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Looping Through and Getting Frequency of Elements in an Array in JavaScript
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 }
Advertisements