Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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 if I tried creating a string instead?

like image 414
Lance Avatar asked Apr 14 '11 04:04

Lance


2 Answers

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
like image 193
David Tang Avatar answered Nov 16 '22 00:11

David Tang


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++;
     }
});
like image 40
saarthak Avatar answered Nov 16 '22 02:11

saarthak