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

I have an array that I compiled in jQuery, and I wonder if there is a way to find the number of occurrences of a given term. Would I have better results if I tried to create a string instead?

+6
source share
4 answers

If you have an array like this:

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

And set the target value:

 var target = 1; 

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

 var numOccurences = $.grep(arr, function (elem) { return elem === target; }).length; // Returns 2 
+34
source

You can probably do 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++; } }); 
+3
source

The method with $ .grep () is more readable and contains fewer lines, but it seems more perfect with a bit 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 metrics are available here: http://jsperf.com/counting-occurrences-of-a-specific-value-in-an-array

+1
source
 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; 
+1
source

Source: https://habr.com/ru/post/885881/


All Articles