Finding out how many times an array element appears

前端 未结 6 1299
既然无缘
既然无缘 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;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 15:00

    Here's an implementation of Juan's answer:

    function count( list, x ) {
    
        for ( var l = list.length, c = 0; l--; ) {
    
            if ( list[ l ] === x ) {
    
                c++;
            }
        }
    
        return c;
    
    }
    

    Even shorter:

    function count( list, x ) {
    
        for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
    
        return c;
    
    }
    
    0 讨论(0)
  • 2020-12-01 15:01

    Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:

    Array.prototype.count = function(lit = false) {
        if ( !lit ) { return this.length}
        else {
            var count = 0;
            for ( var i=0; i < this.length; i++ ) {
                if ( lit == this[i] ){
                    count++
                }
            }
            return count;
        }
    }
    

    This has an extremely simple useage, and is as follows:

    var count = [1,2,3,4,4].count(4);  // Returns 2
    var count = [1,2,3,4,4].count();   // Without first parameter returns 5
    
    0 讨论(0)
  • 2020-12-01 15:05

    Well..

    var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
      if (typeof acc[curr] == 'undefined') {
        acc[curr] = 1;
      } else {
        acc[curr] += 1;
      }
    
      return acc;
    }, {});
    
    // a == {2: 5, 4: 1, 5: 3, 9: 1}
    

    from here: Counting the occurrences of JavaScript array elements

    Or you can find other solutions there, too..

    0 讨论(0)
  • 2020-12-01 15:08

    With filter and length it seems simple but there is a big waste of memory.

    If you want to use nice array methods, the appropriate one is reduce:

    function countInArray(array, value) {
      return array.reduce((n, x) => n + (x === value), 0);
    }
    console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3

    0 讨论(0)
提交回复
热议问题