获取数组JavaScript中出现次数最多的元素 [英] get most occurring elements in array JavaScript

查看:118
本文介绍了获取数组JavaScript中出现次数最多的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要获取最多出现的元素的数组,

I have an array that I want to get the most occurring elements,

第一种情况

First scenario

let arr1 = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz']
let newArr = someFunc(arr1)

所以在这种情况下,我希望新数组具有值

so in this case I want the new array to have the value

console.log(newArr) // ['foo', 'bar'] 

因为值'foo'和'bar'是数组中最常出现的元素

Because the value 'foo' and 'bar' was the most occurring element of the array

第二种情况

Second scenario

 let arr2 = ['foo', 'foo', 'foo', 'bar', 'baz']
 let newArr = someFunc(arr2)

所以在这种情况下,我希望新数组具有值

so in this case I want the new array to have the value

console.log(newArr) // ['foo']

因为值'foo'是数组中最常出现的元素

Because the value 'foo' was the most occurring element of the array

这是我尝试过的方法,即使有多个元素出现相同的时间,也只会让我获得其中一个元素

This is what I have tried and it will only get me one of the elements even if there are more than one element that occurs the same amount of times

newArr= arr.sort((a,b) =>
arr.filter(v => v===a).length
- arr.filter(v => v===b).length
).pop()

推荐答案

您可以使用reduce对项目进行计数,并找到最大出现次数.然后,您可以过滤具有该计数的所有键:

You can count the items with reduce and find the maximum occurring count. Then you can filter any keys that have that count:

let arr = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'];

let counts = arr.reduce((a, c) => {
  a[c] = (a[c] || 0) + 1;
  return a;
}, {});
let maxCount = Math.max(...Object.values(counts));
let mostFrequent = Object.keys(counts).filter(k => counts[k] === maxCount);

console.log(mostFrequent);

这篇关于获取数组JavaScript中出现次数最多的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆