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