Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count instances of string in an array

Tags:

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.

like image 684
Livi17 Avatar asked Apr 03 '12 15:04

Livi17


People also ask

How do you count strings in an array?

Approach: The idea is to iterate over all the strings and find the distinct characters of the string, If the count of the distinct characters in the string is less than or equal to the given value of the M, then increment the count by 1.

How do you count occurrences in an array?

To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .

How do you count occurrences in JavaScript?

In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.


2 Answers

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
like image 26
Selvakumar Arumugam Avatar answered Oct 12 '22 10:10

Selvakumar Arumugam


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;
like image 180
Jamiec Avatar answered Oct 12 '22 11:10

Jamiec