I am currently being faced with this problem where I am trying to find the most occurring or frequent element in an array.
For example:
const arr = [1,2,1,1,1,2,2,2,1] (Most occuring is: 1)
Follow up: What if I want to get the second-most occurring element?
Here's my solution:
function returnMostOccurring(arr) {
const obj = {};
arr.forEach(item => {
if(!obj[item]) obj[item] = 1;
else obj[item]++;
})
const res = Object.entries(obj).sort((a,b) => b[1]-a[1]);
return res.shift();
}
I figured this is not the most optimal way to solve this problem (O(nLogN) time complexity)
What is the best way to handle this kind of use case?