livi1717 livi1717 - 6 months ago 10
jQuery Question

Count instances of string in an array

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.

Answer

Using a basic, old-fashioned loop:

var numOfTrue = 0;
for(var i=0;i<Answers.length;i++){
    if(Answers[i] === "true")
       numOfTrue++;
}

or, a newfangled reduce

var numOfTrue = Answers.reduce(function(p,c){
    if(c === "true")
       p++;
    return p;
},0);