Finding out how many times an array element appears

前端 未结 6 1314
既然无缘
既然无缘 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:59

    • Keep a variable for the total count
    • Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
    • After the loop, total count contains the number of times the number you were looking for is in the array

    Show your code and we can help you figure out where it went wrong

    Here's a simple implementation (since you don't have the code that didn't work)

    var list = [2, 1, 4, 2, 1, 1, 4, 5];  
    
    function countInArray(array, what) {
        var count = 0;
        for (var i = 0; i < array.length; i++) {
            if (array[i] === what) {
                count++;
            }
        }
        return count;
    }
    
    countInArray(list, 2); // returns 2
    countInArray(list, 1); // returns 3
    

    countInArray could also have been implemented as

    function countInArray(array, what) {
        return array.filter(item => item == what).length;
    }
    

    More elegant, but maybe not as performant since it has to create a new array.

提交回复
热议问题