I'm trying to find the most commonly occurring string in a 2D array.
For example, given:
const arr = [['foo','bar','21'],
['foo', 'lar','28'],
['loo', 'bar','28']]
We can see that foo
appears most frequently in column 1, bar
in column 2, and 28
in column 3.
The size of the array may vary, so the solution needs to be dynamic.
I attempted a solution but it's complex and not suitable for multidimensional arrays:
function foo_func(array){
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++){
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
}
return maxEl;
}
If anyone has a cleaner or functional solution, I'd greatly appreciate it!