I have an array that I want to find the number of string 'hello'
in it. Is there any way to do this?
-
I don't understand how this question is different from your earlier one.– user113716Nov 1, 2010 at 23:08
-
@patrick I mean this in the earlier one but I must not have specified well enough because I got answers that only returned the location of the first one in the array. The answers I got on this one are exactly what I wanted.– chromedudeNov 1, 2010 at 23:14
-
You may want to consider deleting that one if it didn't express your issue. :o)– user113716Nov 1, 2010 at 23:35
Add a comment
|
5 Answers
var count = 0;
for(var i=0; i<myArray.length; i++) {
if(myArray[i] == 'hello') {
count++;
}
}
Assuming it's an array of strings,
var count = 0;
for (var i = 0; i < stringArray.length; ++i) {
if (stringArray[i] == "hello")
++count;
}
And now for something completely different functional:
var count = stringArray.filter(function(x) { return x == "hello" }).length
var arr=['no','hello',2,true,false,'hello','true','hello'];
if(arr.indexOf){
var ax= -1, count= 0;
while((ax= arr.indexOf('hello', ax+1))!= -1)++count;
}
alert(count)