Is there any way to count the number of occurrences in a jQuery array?

前端 未结 4 1459
失恋的感觉
失恋的感觉 2021-01-02 08:48

I have an array that I put together in jQuery and I\'m wondering if there is a way that I could find the number of occurrences of a given term. Would I have better results i

相关标签:
4条回答
  • 2021-01-02 09:15
    var x = [1,2,3,4,5,4,4,6,7];
    var item = 4;
    var itemsFound = x.filter(function(elem){
                                return elem == item;
                              }).length;
    

    Or

    var itemsFound = $.grep(x, function (elem) {
                                  return elem == item;
                               }).length;
    
    0 讨论(0)
  • 2021-01-02 09:22

    You can probably do like this -

    var myArray = ['a','fgh','dde','a3e','rra','ab','a'];
    var occurance = 0;
    var lookupVal = 'a';
    $(myArray).each(function (index, value) {
         if(value.indexOf(lookupVal)!= -1) 
         {
            occurance++;
         }
    });
    
    0 讨论(0)
  • 2021-01-02 09:23

    If you have an array like this:

    var arr = [1, 2, 3, 4, 3, 2, 1];
    

    And set your target value:

    var target = 1;
    

    Then you can find the number of occurences of target using:

    var numOccurences = $.grep(arr, function (elem) {
        return elem === target;
    }).length; // Returns 2
    
    0 讨论(0)
  • 2021-01-02 09:33

    Method with $.grep() is more readable and contains fewer lines but it seems more performant with a little more lines in native javascript :

    var myArray = ["youpi", "bla", "bli", "blou", "blou", "bla", "bli", "you", "pi", "youpi", "yep", "yeah", "bla", "bla", "bli", "you", "pi", "youpi", "yep", "yeah", "bla", "bla", "bli", "you", "pi", "youpi", "yep", "yeah", "bla", "bla", "bli", "you", "pi", "youpi", "yep", "yeah", "bla"];
    
    // method 1 
    var nbOcc = 0;
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i] == "bla") {
        nbOcc++;
      }
    }
    console.log(nbOcc); // returns 9
    
    
    // method 2
    var nbOcc = $.grep(myArray, function(elem) {
      return elem == "bla";
    }).length;
    console.log(nbOcc); // returns 9
    

    Js performances are available here : http://jsperf.com/counting-occurrences-of-a-specific-value-in-an-array

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