开发者

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

开发者 https://www.devze.com 2023-02-24 22:39 出处:网络
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 b开发者_C百科etter results if I tried creat

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 b开发者_C百科etter results if I tried creating a string instead?


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


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++;
     }
});


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


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

精彩评论

暂无评论...
验证码 换一张
取 消