我想知道如何获取二维数组中出现频率最高的字符串?
例如,如果您有:
const arr = [['foo','bar','21'],
['foo', 'lar','28'],
['loo', 'bar','28']]
您会看到在第 1 列中 foo
是最常出现的字符串,第二列是 bar
,第三列是 28
我的数组可能并不总是这个大小,所以我需要让它可以采用任何大小。
这是我尝试过的方法,但它很大并且不适用于 2 维:
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;
}
如果有人有更简洁或有效的解决方案,我们将不胜感激!
最佳答案
你可以reduce
成一个数组,它的值是对象,它的键是属性(例如'foo'
),它的值是它出现的次数在当前列中键入:
const arr = [
['foo', 'bar', '21'],
['foo', 'lar', '28'],
['loo', 'bar', '28']
];
const columns = arr.reduce((a, subarr) => {
subarr.forEach((item, i) => {
if (!a[i]) a[i] = {};
a[i][item] = (a[i][item] || 0) + 1;
});
return a;
}, {});
const highestInEachColumnEntries = Object.values(columns).map(
obj => Object.entries(obj)
.reduce(
(a, b) => a[1] > b[1] ? a : b
)
);
const highestInEachColumnKeysOnly = highestInEachColumnEntries.map(([key]) => key);
console.log(highestInEachColumnKeysOnly);
关于javascript - 在javascript中使用二维数组获得最高频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55911596/