How to use Object In Javascript
In this approach we will use JavaScript object to store the number and their occurences and find the element occurred most frequently.
Example:
const arr = [
1, 1, 3, 5, 7, 6, 8, 5, 6, 4,
7, 6, 0, 2, 1, 6, 8, 9, 5,
];
obj = {};
let el,
max = 0;
for (let i = 0; i < arr.length; i++) {
if (!obj[arr[i]]) obj[arr[i]] = 1;
else obj[arr[i]]++;
}
for (const i in obj) {
if (max < obj[i]) {
max = obj[i];
el = i;
}
}
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.