Finding out how many times an array element appears

前端 未结 6 1310
既然无缘
既然无缘 2020-12-01 14:50

I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I\'m making a poker game and what I\'m trying to d

6条回答
  •  天命终不由人
    2020-12-01 14:52

    When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)

    var items = [1, 2, 3, 4, 4, 4, 3];
    var fours = items.filter(function(it) {return it === 4;});
    var result = fours.length;
    

    You can even abstract over the filtering function as this:

    // Creates a new function that returns true if the parameter passed to it is 
    // equal to `x`
    function equal_func(x) {
        return function(it) {
            return it === x;
        }
    }
    //...
    var result = items.filter(equal_func(4)).length;
    

提交回复
热议问题