Suppose a Particular JavaScript array Contains list of (More than 15) numeric and character value i.e [1,2,3,4,’A’,’B’,’C’,’A’,’A’,’A’,1,1,3,3,’D’,’D’,’E’]
Write a JavaScript Program to find out the most frequent elements in that array.
Solution:
function findMostFrequentElements(arr) {
const frequencyMap = new Map();
// Count the frequency of each element in the array
arr.forEach(item => {
if (frequencyMap.has(item)) {
frequencyMap.set(item, frequencyMap.get(item) + 1);
} else {
frequencyMap.set(item, 1);
}
});
// Find the maximum frequency
let maxFrequency = 0;
frequencyMap.forEach(value => {
if (value > maxFrequency) {
maxFrequency = value;
}
});
// Find elements with the maximum frequency
const mostFrequentElements = [];
frequencyMap.forEach((value, key) => {
if (value === maxFrequency) {
mostFrequentElements.push({ item: key, frequency: value });
}
});
return mostFrequentElements;
}
const inputArray = [1, 2, 3, 4, 'A', 'B', 'C', 'A', 'A', 'A', 1, 1, 3, 3, 'D', 'D', 'E'];
const mostFrequent = findMostFrequentElements(inputArray);
mostFrequent.forEach(item => {
console.log(`Array item ${item.item} , appears ${item.frequency} times`);
});
Output: Most frequent elements in that array
To get more such solutions, simply contact us and we’ll provide you with a quote and estimated turnaround time.
Our team is dedicated to delivering high-quality work that meets your expectations and helps you achieve your academic goals.
Hire an expert for JavaScript homework help work.