
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 all the elements in an array 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 }
- Related Questions & Answers
- Looping through an array in Javascript
- Building frequency map of all the elements in an array JavaScript
- How to loop through all the elements of an array in C#?
- Looping through the content of a file in Bash
- Getting elements of an array depending on corresponding values of another JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Return an array of all the indices of minimum elements in the array in JavaScript
- Frequency of smaller and larger elements - JavaScript
- Looping numbers with object values and push output to an array - JavaScript?
- Frequency distribution of elements - JavaScript
- Looping through a dynamic table in SAP
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- JavaScript Checking if all the elements are same in an array
- Go through an array and sum only numbers JavaScript
Advertisements