我正在关注这个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/