How to use Map and forEach method In Javascript
In this method, we will use JavaScript Map to map the values with number of occurrences and print the maximum occurred element
Example:
const arr = [
3, 5, 7, 6, 8, 5, 6, 4, 7, 1,
6, 0, 2, 1, 6, 8, 9, 5, 1,
];
let m = new Map();
for (const i in arr) {
if (!m.get(arr[i])) m.set(arr[i], 1);
else {
m.set(arr[i], m.get(arr[i]) + 1);
}
}
let max = 0;
let el;
m.forEach((val, key, map) => {
if (max < val) {
max = val;
el = key;
}
});
console.log("The most occured element is: " + el);
Output
The most occured element is: 6
Most Frequent Element in an Array using JavaScript
We will demonstrate different methods to find the most frequent element in an array in JavaScript. We will be given an array with multiple occurrences of values in that array and we have to output the maximum occurred element in that array.
Contact Us