You don't need jQuery for this task. Just plain Javascript. The best answer is given by Jamiec by you could also use filter or reduce functions that are available for arrays.
filter function:
var numOfTrue = Answers.filter(function(item){ return item === "true"; }).length
Here you are providing callback function that is executed for every item in array. If this function returns true
then this item will be in returned array. Then you get the length of this array ( length of ["true", "true"]
array is 2
)
reduce function:
var numOfTrue = Answers.reduce(function(counter, item){ return counter + (item === "true" ? 1 : 0); }, 0);
Reduce function need callback function that is executed for every item in array. Array item is provided as second argument, the first one is the return value of previously executed callback. The second argument of reduce function is initial value that is provided for first callback function. If you omit this, then the first item from array is provided (in this example, if you forget to add 0
as second argument then the result value will be "true0010"
string, because instead of adding numbers you will be concatenating stings)
.each()
to loop, and.filter()
or.map()
to be more functional. But do you really need to use jQuery?