2016-09-28 53 views
0

如何過濾並找到一個從我的數組中重複3次的數字?Javascript過濾一個匹配值的數組

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> 
+0

整整3倍? – Li357

+0

是的,我覺得我正朝着正確的方向前進,但不知道如何讓它意識到某個數字被輸出了3次。 – Gianni

+0

是[this](https://jsbin.com/raholiqeni/edit?html,js,console,output)這個想法?三聯發生次數推三次,你可以很容易地調整它。 – Li357

回答

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] 
+2

我認爲OP正試圖檢索重複3次的數字。無論如何,好的答案! – Li357

+1

@AndrewL。由於更新的! – ryanve

相關問題