Gianni
Gianni

Reputation: 136

Javascript filter an array with matching values

How could I filter and find a number that is repeated 3 times from my array?

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>

Upvotes: 1

Views: 2294

Answers (1)

ryanve
ryanve

Reputation: 52601

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]

Upvotes: 4

Related Questions