Javascript过滤具有匹配值的数组

时间:2016-09-28 00:12:23

标签: javascript

我怎样才能过滤并找到一个从我的数组中重复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:

<button onClick="produceChanceNumbers()">1</button>

1 个答案:

答案 0 :(得分:4)

我为您的过滤器编写了一个单独的函数,如

function filterByCount(array, count) {
    return array.filter(function(value) {
        return array.filter(function(v) {
          return v === value
        }).length === count
    })
}

你可以使用

filterByCount([1, 1, 8, 1], 3) // [1, 1, 1]
filterByCount([1, 1, 8, 1], 1) // [8]