[英]Javascript filter an array with matching values
How could I filter and find a number that is repeated 3 times from my array? 如何过滤并从数组中查找重复3次的数字?
function produceChanceNumbers(){
//initiate array
var arr = [];
//begin running 10 times
for (var i = 0, l = 10; i < l; i++) {
arr.push(Math.round(Math.random() * 10));
}
console.log(arr);
//inputs array in html element
document.getElementById("loop").innerHTML = arr.join(" ");
var winner =
//begin filtering but only replaces numbers that repeat
console.log(arr.filter(function(value, index, array){
return array.indexOf(value) === index;
}));
}//end produceChanceNumbers
html: HTML:
<button onClick="produceChanceNumbers()">1</button>
I'd write a separate function for your filter like 我会为您的过滤器编写一个单独的函数,例如
function filterByCount(array, count) {
return array.filter(function(value) {
return array.filter(function(v) {
return v === value
}).length === count
})
}
that you could use like 你可以使用像
filterByCount([1, 1, 8, 1], 3) // [1, 1, 1]
filterByCount([1, 1, 8, 1], 1) // [8]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.