I was attempting to solve a common problem involving finding the most popular item in an array.
While I came across some O(n) solutions using maps, none seemed to work effectively when dealing with mixed data types such as:
[1,2,1,3,"1","a"]
The issue arises when "1" is considered equal to 1. Is there any way to customize comparison within JS? Or is there an O(n) solution that can address this?
The focus here is on finding the most frequent element in the array, bearing in mind that there may be multiple elements with the same frequency:
function getMostFrequent(array) {
if (array.length == 0)
return null;
let mapEl = {};
let maxEl = [];
let maxCount = 1;
for (let i = 0; i < array.length; i++) {
let el = array[i];
if (mapEl[el] == null) {
mapEl[el] = 1;
} else {
mapEl[el]++;
}
if (mapEl[el] > maxCount) {
maxCount = mapEl[el];
maxEl = [el];
} else if (mapEl[el] === maxCount) {
maxEl.push(el);
}
}
console.log(maxEl);
return maxEl;
}