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.

4
  • 1
    No jQuery required here, this is javascript country. Commented 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? Commented 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. Commented Apr 3, 2012 at 15:46
  • Thanks for the clarification, Rocket. I used one of the javascript examples below. Commented Apr 3, 2012 at 15:56

14 Answers 14

66

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;
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@CodedContainer then you have a different question to this one ;)
12

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 Comment

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/…
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 Comments

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...
@Samich - It is also possible to do this in pure JavaScript: Answers.filter(function(v){ return v === "true"; }).length;
@JustinEthier FYI .filter is not compatible with IE 8. :( kangax.github.com/es5-compat-table
@SKS - Good to know, thanks. In any case this is more of a curiosity - the best solution is to just use a for loop.
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 Comment

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

Comments

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++;
});

Comments

1
var numOfTrue =0;
$.each(Answers,function(index,value){
   if(value =="true")
   {
      numOfTrue++;
   }
});

http://jsfiddle.net/3PpJS/

4 Comments

$.each on what? You need to change that to $.each(Answers, ...)
I noticed it after I posted. Your quick!
Well, the thing is.. someone saw $.each and voted up.. even though it was not correct(initially)
It would probably be better to use === instead of ==
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/

Comments

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

2 Comments

@Nicosunshine - There is no need to use jQuery for simple stuff like this.
It was a joke :) look at this: doxdesk.com/img/updates/20091116-so-large.gif
1
arr = [true,true,true,false,false]
n = arr.join('').split("true").length-1

Comments

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/

Comments

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.