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>
5
  • 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. Commented Sep 28, 2016 at 0:16
  • Is this the idea? The triplet-occurrence numbers push 3 times, you can easily tweak it. Commented Sep 28, 2016 at 0:24
  • See this question for getting unique values. Commented Sep 28, 2016 at 0: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 Commented Sep 28, 2016 at 0: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! Commented Sep 28, 2016 at 0:34

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I think the OP is trying to retrieve the number which is repeated 3 times. Regardless, nice answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.