Get the number of true/false values in an array using JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

To get the number of true/ false values in an array, the code is as follows −

var obj = [
   {
      isMarried: true
   },
   {
      isMarried: false
   },
   {
      isMarried: true
   },
   {
      isMarried: true
   },
   {
      isMarried: false
   }
]
function numberOfTrueValues(obj) {
   var counter = 0;
   for (var index = 0; index < obj.length; index++) {
      if (obj[index].isMarried === true) {
         counter++;
      }
   }
   return counter;
}
function numberOfFalseValues(obj) {
   var counter = 0;
   for (var index = 0; index < obj.length; index++) {
      if (obj[index].isMarried === false) {
         counter++;
      }
   }
   return counter;
}
console.log("Number Of true values=" + numberOfTrueValues(obj));
console.log("Number Of false values=" + numberOfFalseValues(obj));

To run the above program, you need to use the below command −

node fileName.js.

Here, my file name is demo318.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo318.js
Number Of true values=3
Number Of false values=2
raja
Published on 26-Oct-2020 15:54:49
Advertisements