我正在寻找一种优雅的方法来确定哪个元素在JavaScript数组中出现次数最多(模式).
例如,在
['pear', 'apple', 'orange', 'apple']
Run Code Online (Sandbox Code Playgroud)
'apple'元素是最常见的元素.
Mat*_*hen 76
这只是模式.这是一个快速,非优化的解决方案.它应该是O(n).
function mode(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;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
Run Code Online (Sandbox Code Playgroud)
Emi*_*ary 44
自2009年以来,javascript已经有了一些发展 - 我想我会添加另一种选择.我不太关心效率,直到它实际上是一个问题所以我对"优雅"代码的定义(由OP规定)有利于可读性 - 这当然是主观的......
function mode(arr){
return arr.sort((a,b) =>
arr.filter(v => v===a).length
- arr.filter(v => v===b).length
).pop();
}
mode(['pear', 'apple', 'orange', 'apple']); // apple
Run Code Online (Sandbox Code Playgroud)
在这个特定的例子中,如果集合中的两个或多个元素具有相同的出现次数,那么将返回数组中最新出现的元素.同样值得指出的是,它会修改你原来的阵列 - 如果你希望Array.slice事先打电话,这可以防止 .
编辑:使用一些ES6 胖箭更新了示例,因为2015年发生了,我认为它们看起来很漂亮......如果您关注向后兼容性,可以在修订历史中找到它.
sam*_*ore 32
根据George Jempty's请求将算法考虑为关系,我提出了Matthew Flaschen's算法的修改版本.
function modeString(array)
{
if (array.length == 0)
return null;
var modeMap = {},
maxEl = array[0],
maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if (modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if (modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
else if (modeMap[el] == maxCount)
{
maxEl += '&' + el;
maxCount = modeMap[el];
}
}
return maxEl;
}
Run Code Online (Sandbox Code Playgroud)
现在,这将返回一个字符串,其中模式元素由'&'符号分隔.收到结果后,可以在该'&'元素上拆分,然后就可以使用您的模式.
另一个选择是返回一个模块元素数组,如下所示:
function modeArray(array)
{
if (array.length == 0)
return null;
var modeMap = {},
maxCount = 1,
modes = [];
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if (modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if (modeMap[el] > maxCount)
{
modes = [el];
maxCount = modeMap[el];
}
else if (modeMap[el] == maxCount)
{
modes.push(el);
maxCount = modeMap[el];
}
}
return modes;
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,您将能够将函数的结果作为模式数组来处理.
Thi*_*ker 12
a=['pear', 'apple', 'orange', 'apple'];
b={};
max='', maxi=0;
for(let k of a) {
if(b[k]) b[k]++; else b[k]=1;
if(maxi < b[k]) { max=k; maxi=b[k] }
}
Run Code Online (Sandbox Code Playgroud)
小智 10
根据Emissary的ES6 +答案,你可以用Array.prototype.reduce你的比较(而不是排序,弹出和可能改变你的数组),我认为这看起来很光滑.
const mode = (myArray) =>
myArray.reduce(
(a,b,i,arr)=>
(arr.filter(v=>v===a).length>=arr.filter(v=>v===b).length?a:b),
null)
Run Code Online (Sandbox Code Playgroud)
我默认为null,如果null是你正在过滤的可能选项,那么这并不会总是给你一个真实的答案,也许这可能是一个可选的第二个参数
与其他各种解决方案一样,缺点是它不能处理"绘制状态",但这仍然可以通过稍微复杂的减少功能来实现.
由于我将此功能用作面试官的测验,因此我发布了我的解决方案:
const highest = arr => (arr || []).reduce( ( acc, el ) => {
acc.k[el] = acc.k[el] ? acc.k[el] + 1 : 1
acc.max = acc.max ? acc.max < acc.k[el] ? el : acc.max : el
return acc
}, { k:{} }).max
const test = [0,1,2,3,4,2,3,1,0,3,2,2,2,3,3,2]
console.log(highest(test))
Run Code Online (Sandbox Code Playgroud)
该解决方案具有O(n)复杂性:
function findhighestOccurenceAndNum(a) {
let obj = {};
let maxNum, maxVal;
for (let v of a) {
obj[v] = ++obj[v] || 1;
if (maxVal === undefined || obj[v] > maxVal) {
maxNum = v;
maxVal = obj[v];
}
}
console.log(maxNum + ' has max value = ' + maxVal);
}
findhighestOccurenceAndNum(['pear', 'apple', 'orange', 'apple']);Run Code Online (Sandbox Code Playgroud)
在这里尝试声明式方法。该解决方案构建了一个对象来计算每个单词的出现次数。然后,通过将每个单词的总出现次数与对象中找到的最大值进行比较,将对象过滤为一个数组。
const arr = ['hello', 'world', 'hello', 'again'];
const tally = (acc, x) => {
if (! acc[x]) {
acc[x] = 1;
return acc;
}
acc[x] += 1;
return acc;
};
const totals = arr.reduce(tally, {});
const keys = Object.keys(totals);
const values = keys.map(x => totals[x]);
const results = keys.filter(x => totals[x] === Math.max(...values));
Run Code Online (Sandbox Code Playgroud)