1

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>
Gianni
  • 136
  • 1
  • 14
  • Yes, I feel like im headed in the right direction but don't know how I can make it realize that a certain number was outputted 3 times. – Gianni Sep 28 '16 at 00:16
  • Is [this](https://jsbin.com/raholiqeni/edit?html,js,console,output) the idea? The triplet-occurrence numbers push 3 times, you can easily tweak it. – Andrew Li Sep 28 '16 at 00:24
  • See [this](http://stackoverflow.com/questions/11246758/how-to-get-unique-values-in-an-array) question for getting unique values. – Andrew Li Sep 28 '16 at 00:31
  • Oh yes actually that your js bin worked perfectly. So it is grabbing that array then just producing another array with the number that matched 3 times. That is really cool. Thank you – Gianni Sep 28 '16 at 00:33
  • 1
    make sure to change the condition to be **exactly 3**, right now it's greater than or equal to 3, and no problem! – Andrew Li Sep 28 '16 at 00:34

1 Answers1

4

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]
ryanve
  • 50,076
  • 30
  • 102
  • 137