24

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.

4
  • 1
    No jQuery required here, this is javascript country. Apr 3, 2012 at 15:44
  • 3
    You can use .each() to loop, and .filter() or .map() to be more functional. But do you really need to use jQuery? Apr 3, 2012 at 15:44
  • 3
    You don't have an "array in jQuery", you have an "array in JavaScript". You are programming in the JavaScript language; you are just using the jQuery library.
    – gen_Eric
    Apr 3, 2012 at 15:46
  • Thanks for the clarification, Rocket. I used one of the javascript examples below.
    – Livi17
    Apr 3, 2012 at 15:56

14 Answers 14

62

Using a basic, old-fashioned loop:

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

or, a reduce

var numOfTrue = Answers.reduce((acc,curr) => {
    if(curr === "true")
       acc++;
    return acc;
},0);

or a filter

var numOfTrue = Answers.filter(x => x === "true").length;
2
  • 2
    this is great if you are going to be looking for a value you already know but what happens if you have several random items in an array? Apr 18, 2016 at 15:53
  • 1
    @CodedContainer then you have a different question to this one ;)
    – Jamiec
    Sep 30, 2016 at 10:37
11

You don't need jQuery for this.. a simple for loop like below would do the trick,

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

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

or even without a loop, DEMO

Answers.toString().match(/true/g).length
1
  • 2
    A more universal solution would be Answers.join(',').match(/(?:,|^)true(?:,|$)/g).length. This will handle situations where one term may be a sub-string of another (i.e. the array contains both "true" and "truest" and you only want to count the exact string "true"). Regex demo: regexpal.com/…
    – craigpatik
    Feb 12, 2014 at 14:15
7

It might be not so performance friendly but you can use filtering and then count using grep:

var num = jQuery.grep(Answers, function (a) { return a == "true"; }).length;
4
  • Not as efficient as a for loop or each, but I like how you were able to get it down to 1 line :). FWIW if jQuery had a reduce method you might be able to create an efficient one-liner... Apr 3, 2012 at 15:56
  • 2
    @Samich - It is also possible to do this in pure JavaScript: Answers.filter(function(v){ return v === "true"; }).length; Apr 3, 2012 at 16:02
  • @JustinEthier FYI .filter is not compatible with IE 8. :( kangax.github.com/es5-compat-table Apr 3, 2012 at 16:09
  • @SKS - Good to know, thanks. In any case this is more of a curiosity - the best solution is to just use a for loop. Apr 3, 2012 at 16:33
7

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)

1
  • I like the one-liner, but be careful: filter and reduce don't work in older browsers, e.g. IE 8 or below. One could consider using JQuery's grep option, though. Jun 4, 2015 at 20:07
2

You can also use regular expressions and the String.prototype.match()

Code:

const Answers = [ "true", "false", "false", "true", "false" ];
const count = Answers.toString().match(/true/g).length;

console.log(count)

1

If you did want to use jQuery (and tbh, you shouldn't for this) this will work:

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

$.each(Answers, function(i, item) {
    if (item == "true")
        numOfTrue++;
});

The Javascript equivalent is:

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

for (var i = 0; i < Answers.length; i++) {
    if (answers[i] == "true")
        numOfTrue++;
});
1
var numOfTrue =0;
$.each(Answers,function(index,value){
   if(value =="true")
   {
      numOfTrue++;
   }
});

http://jsfiddle.net/3PpJS/

4
  • $.each on what? You need to change that to $.each(Answers, ...) Apr 3, 2012 at 15:46
  • I noticed it after I posted. Your quick! Apr 3, 2012 at 15:49
  • Well, the thing is.. someone saw $.each and voted up.. even though it was not correct(initially) Apr 3, 2012 at 15:50
  • It would probably be better to use === instead of == Apr 3, 2012 at 15:53
1
var numOfTrue;
var Answers = [ "true", "false", "false", "true", "false" ];
var i = 0;
$.each(Answers, function(index, value){
    if(value == "true")
    {
        i++;
    }
});


alert(i);

http://jsfiddle.net/kpcrash/Xxcw6/

1
var numOfTrue = 0;
for(var i = 0, len = Answers.length;i < len; i++){
    if(Answers[i] === "true"){
       numOfTrue++;
    }
}
2
1
arr = [true,true,true,false,false]
n = arr.join('').split("true").length-1
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/

0

Using only JS

function Count(targetString){
var vowels = ['a','o','u','i','e'];

   return targetString.split("").reduce(function(countingVaues,char){
   countingVaues += 
   vowels.filter(function(x){return x === char;}).length;
   return countingVaues;
   },0)};

Count("aouiesndfjksdnjkfnsdjkewwe"); //==7
0

If you're looking for counting more varied array I think you can implement your code as follow:

    var numOfTrue;
    var i=0;
    var Answers = [ "true", "false", "not sure", "false", "true", "false", "not sure", "I don't know" ];
    var counted = [];
    var result = {};
    Answers.forEach(answer => {// refer to each item in this array with the parameter "answer"
        if(!counted.includes(answer)){ // check if answer is not in counted array
            counted.push(answer); // add the answer to counted [array]
            result[answer] = 1; // add answer to result{object} as a key with a value of 1
        }else if(counted.includes(answer)){// here we check if answer is in counted [array]

    // if it's true, that means we have already set its value in the result{object} to 1
            result[answer] += 1    // now, we just need to increment its value by 1
        }
    })

    console.log(result); // {true: 2, false: 3, not sure: 2, I don't know: 1}
    numOfTrue = result.true;
    console.log(numOfTrue);// 2
0

var Answers = [ "true", "false", "not sure", "false", "true", "false", "not sure", "I don't know" ];

function maxDuplicateCountInstances(_arr){
const temp={};
const uniqueArrayKeyToCompare = Array.from(new Set(_arr));
let compareKey='';
console.log('Individually Count');
uniqueArrayKeyToCompare.forEach((unqKey)=>{
  const filterOutArray = _arr.filter((key)=>key===unqKey);
  temp.name = unqKey;
  temp.count = filterOutArray.length;
  console.log(temp.name,temp.count);
});
}
maxDuplicateCountInstances(Answers);

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.