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

前端 未结 4 1581
失恋的感觉
失恋的感觉 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: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

提交回复
热议问题