- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Figuring out the highest value through a for in loop - JavaScript
Suppose, we have a comma separator string that contains some fruit names like this −
const str = 'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grape,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,Grape,Orange,Orange,Apple,Apple,Banana';
We are required to write a JavaScript function that takes in one such string and uses the for in loop to figure out the fruit name that appears for the greatest number of times in the string.
The function should return the fruit string that appears for most number of times.
Example
Following is the code −
const str = 'Banana,Banana,Pear,Orange,Apple,Melon,Grape,Apple,Banana,Grape,Melon,Grap e,Melon,Apple,Grape,Banana,Orange,Melon,Orange,Banana,Banana,Orange,Pear,G rape,Orange,Orange,Apple,Apple,Banana'; const findMostFrequent = str => { const strArr = str.split(','); const creds = strArr.reduce((acc, val) => { if(acc.has(val)){ acc.set(val, acc.get(val) + 1); }else{ acc.set(val, 1); }; return acc; }, new Map()); return Array.from(creds).sort((a, b) => b[1] - a[1])[0][0]; }; console.log(findMostFrequent(str));
Output
This will produce the following output in console −
Banana
- Related Articles
- Loop through a Dictionary in Javascript
- Loop through a Set using Javascript
- Loop through a hash table using Javascript
- How to use for...in statement to loop through an Array in JavaScript?
- Loop through an index of an array to search for a certain letter in JavaScript
- Loop through array and edit string JavaScript
- Returning the highest value from an array in JavaScript
- Returning the highest number from object properties value – JavaScript
- Reversing a string using for loop in JavaScript
- How to use the break statement to come out of a loop in JavaScript?
- Multiple Variables Holding Data - Which has the Highest Value in JavaScript?
- Highest and lowest value difference of array JavaScript
- Explain for. . .of loop JavaScript.
- Loop through ArrayList in Java
- How to use for each loop through an array in Java?

Advertisements