我正在关注此Counting the occurrences of JavaScript 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次以上? 感谢
答案 0 :(得分:4)
您可以使用reduce
方法轻松解决此问题。 reduce
方法通过应用提供的回调函数来创建新数组或对象。
reduce()
方法对累加器应用函数 数组中的每个元素(从左到右)将其减少为a 单一价值。
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);
}
&#13;
答案 1 :(得分:1)
试试这段代码:
var countries = ["India" , "Australia" , "Bangladesh" , "India" , "India" , "New Zealand" , "New Zealand" , "Pakistan" , "Pakistan" , "West Indies","New Zealand"];
var recipientsArray = countries.sort();
checkedWords = [];
for (var i = 0; i < recipientsArray.length; ++i) {
var count = 0;
for(var j=i;j<recipientsArray.length;j++){
if(checkedWords.indexOf(recipientsArray[i]) > -1){
continue;
}
if(recipientsArray[i] == recipientsArray[j]){
count = count+1;
}
}
console.log(count);
if(count >= 3){
alert(recipientsArray[i]);
}
checkedWords.push(recipientsArray[i]);
}
https://jsfiddle.net/74bzzze3/
我希望这能回答你的问题:)
答案 2 :(得分:0)
const array = ['India' , 'Australia' , 'Bangladesh' , 'India' , 'India' , 'New Zealand' , 'New Zealand' , 'Pakistan' , 'Pakistan' , 'West Indies'];
_.each(_.uniq(_.filter(array, function(v) {
return _.filter(array, function(v1) {
return v1 === v;
}).length > 2;
})), function(i) {
console.log(i);
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
&#13;
使用UnderscoreJS:
_.uniq(_.filter(array, v =>
_.filter(array, v1 => v1 === v).length > 2));
<强>代码强>
_.each(_.uniq(_.filter(array, function(v) {
return _.filter(array, function(v1) {
return v1 === v;
}).length > 2;
})), function(i) {
console.log(i);
});