1

I have an array that I want to find the number of string 'hello' in it. Is there any way to do this?

3
  • I don't understand how this question is different from your earlier one.
    – user113716
    Nov 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.
    – chromedude
    Nov 1, 2010 at 23:14
  • You may want to consider deleting that one if it didn't express your issue. :o)
    – user113716
    Nov 1, 2010 at 23:35

5 Answers 5

2
var count = 0;
for(var i=0; i<myArray.length; i++) {
    if(myArray[i] == 'hello') {
        count++;
    }
}
0
2

Assuming it's an array of strings,

var count = 0;
for (var i = 0; i < stringArray.length; ++i) {
  if (stringArray[i] == "hello")
    ++count;
}
0

And now for something completely different functional:

var count = stringArray.filter(function(x) { return x == "hello" }).length

0
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)
0

Or

var count = stringArray.reduce(function(a,b){ return (b=='hello')?a+1:a},0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.