JavaScript: Find the most frequent item of an array
JavaScript Array: Exercise-8 with Solution
Write a JavaScript program to find the most frequent item in an array.
Sample array: var arr1=[3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
Sample Output: a ( 5 times )
Visual Presentation:
Sample Solution:
JavaScript Code:
// Declare and initialize the original array
var arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
// Initialize variables to track the most frequent item, its frequency, and the current item's frequency
var mf = 1;
var m = 0;
var item;
// Iterate through the array to find the most frequent item
for (var i = 0; i < arr1.length; i++) {
// Nested loop to compare the current item with others in the array
for (var j = i; j < arr1.length; j++) {
// Check if the current item matches with another item in the array
if (arr1[i] == arr1[j])
m++;
// Update the most frequent item and its frequency if the current item's frequency is higher
if (mf < m) {
mf = m;
item = arr1[i];
}
}
// Reset the current item's frequency for the next iteration
m = 0;
}
// Output the most frequent item and its frequency
console.log(item + " ( " + mf + " times ) ");
Output:
a ( 5 times )
Flowchart:
ES6 Version:
// Declare and initialize the original array
const arr1 = [3, 'a', 'a', 'a', 2, 3, 'a', 3, 'a', 2, 4, 9, 3];
// Initialize variables to track the most frequent item, its frequency, and the current item's frequency
let mf = 1;
let m = 0;
let item;
// Iterate through the array to find the most frequent item
for (let i = 0; i < arr1.length; i++) {
// Nested loop to compare the current item with others in the array
for (let j = i; j < arr1.length; j++) {
// Check if the current item matches with another item in the array
if (arr1[i] == arr1[j])
m++;
// Update the most frequent item and its frequency if the current item's frequency is higher
if (mf < m) {
mf = m;
item = arr1[i];
}
}
// Reset the current item's frequency for the next iteration
m = 0;
}
// Output the most frequent item and its frequency
console.log(item + " ( " + mf + " times ) ");
Live Demo:
See the Pen JavaScript - Find the most frequent item of an array- array-ex- 8 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript program to sort the items of an array.
Next: Write a JavaScript program which accept a string as input and swap the case of each character.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-array-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics