Alex Rivera | Logout

Count instances of string in an array

Asked 2012-04-03T15:41:06.490
25

I have an array in jQuery, and I need to count the number of "true" strings in that array, and then make the "numOfTrue" variable equal the number of true strings. So in the below array, there are 2 "true" strings, so numOfTrue would be equal to 2.

var numOfTrue;
var Answers = [ "true", "false", "false", "true", "false" ];

I'm not sure how to do a loop through the array in jQuery to count the strings. Or is a loop even necessary?

The number of true strings could change from anywhere between 1 to 5.

Edit
Report

1 Answer

0

You can use jQuery.each to iterate over the list, for example:

var Answers = [ "true", "false", "false", "true", "false" ];
var numOfTrue = countTrue(Answers);

alert(numOfTrue);

function countTrue(Answers){
 var numOfTrue = 0;
 jQuery.each( Answers, function(i, value) {
    if (value === "true")
        numOfTrue++;
 });

 return numOfTrue;
}

Here is a jsfiddle if you want to play around with it: http://jsfiddle.net/HHrwc/

answered 2012-04-03T15:48:09.543

Your Answer