javascript - 使用 jquery 检查数组中的项目数

标签 javascript jquery arrays function

我正在关注这个Counting the occurrences / frequency of array elements找到出现的情况 数组中的每个项目。 如果任何项目出现超过或等于 3 次,那么我必须显示警报。

下面是我尝试过的代码:

var countries = ['India', 'Australia', 'Bangladesh', 'India', 'India',
  'New Zealand', 'New Zealand', 'Pakistan', 'Pakistan', 'West Indies'];

var recipientsArray = countries.sort();

var reportRecipientsDuplicate = [];
for (var i = 0; i < recipientsArray.length; ++i) {
  if (!reportRecipientsDuplicate[recipientsArray[i]]) {
    reportRecipientsDuplicate[recipientsArray[i]] = 0;
  }
  ++reportRecipientsDuplicate[recipientsArray[i]];
}

如何检查某个项目是否出现超过或等于3次?谢谢

最佳答案

您可以使用reduce方法来简单地解决这个问题。 reduce 方法通过应用提供的回调函数创建一个新的数组或对象。

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

var countries = ['India' , 'Australia' , 'Bangladesh' , 'India' , 'India' , 'New Zealand' , 'New Zealand' , 'Pakistan' , 'Pakistan' , 'West Indies'];
var statistics=countries.reduce(function(obj,elem){
    obj[elem]=obj[elem] || 0;
    obj[elem]++;
    return obj;
},{});
for(country in statistics){
  if(statistics[country]>=3)
    console.log(country);
} 

关于javascript - 使用 jquery 检查数组中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43757744/

相关文章:

javascript - jQuery Datatables 过滤器外部表包装的问题

javascript - 为什么jquery不响应我的条件?

php - 我应该使用 $_GET 来动态加载 html 吗?

javascript - Angular 中如何从 json 中获取数据分页

c - C中的for循环只返回数组的第一个值

Javascript 设置变量和对象以及正确的语法(调试控制台)

javascript - 对 drupal 模块的 Ajax 调用不起作用

javascript - jqGrid 返回 rowObject 未定义

javascript - 使用 URL 哈希重新定义 XSS 攻击中的转义函数

java - Android - Eclipse : Syntax error on token "(", 此标记后应有表达式