简体   繁体   中英

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

I'm having an Array with properties id and value

 var arrayObj=  [
        {"id": 1, "value": true},
        {"id": 2, "value": false},
        {"id": 3, "value": true}
    ]

I need to get the number of objects that has the property true / false . I'm using Array.prototype.every() but my logic is not working as intended as it seems. Can anyone tell me what I'm doing wrong here? I'm not displaying the count

function checkIfFalse(value, index, ar) {
     document.write(value + " ");
     if (value  === false)
         return true;
     else
        return false;
}

if (arrayObj.every(checkIfFalse)) {
    console.log("all are false");
}else {
    console.log("all are true");
}

Why not using .filter ?

 // Your array object var arrayObj = [ {"id": 1, "value": true}, {"id": 2, "value": false}, {"id": 3, "value": true} ]; // Count true items var count = arrayObj.filter(function(s) { return s.value; }).length; // Result console.log("#True: " + count);

you can do like this

int falses=0,trues=0;
for(i=0;i<arrayObj.length;i++) {
    if(arrayObj[i].value) {
        trues++;
    } else {
        falses++;
    }
}
console.log('Trues: '+trues+' Falses:'+falses);

the .every() function is expecting being passed an function which will test each item of the array and return true or false. you would want something like:

  if (arrayObj.every(checkIfFalse)) {
                console.log("all are false");
  }

 function checkIfFalse(value, index, ar) {
   console.log('checking if' + index + ' from array is false');
   return value.value == false;
 }

so, arrayObj.every(checkIfFalse) will return false , because not all items are false

.every() is used to check if EVERY item of an array meets a certain condition, it sounds like you want to get a count of the number of items which meet a certain condition. There is no way to do this without iterating through each item of the array and checking. Thhis will be best if you just write your own for loop. ex:

function countItemsTrue(arry){
   var result = 0;
   for(x = 1; arry.length >= x; x++){
      if(arry[x].value === true){
        result++;
      }
   }
   return result;

}

then you would do

  var count = CountItemsTrue(arrayObj);

when it's written like this you can easily check if all are true without iterating all over just by checking:

  var allTrue = count == arrayObj.length;

 var arrayObj = [{ "id": 1, "value": true }, { "id": 2, "value": false }, { "id": 3, "value": true }]; var trueCount = falseCount = 0; arrayObj.forEach(function(object) { object.value === true ? trueCount++ : falseCount++; }); console.log(trueCount, falseCount);

DEMO

 var arrayObj = [{ "id": 1, "value": true }, { "id": 2, "value": false }, { "id": 3, "value": true } ]; Array.prototype.numBoolean = function(condition) { var counter = 0; for (var i = 0; i < this.length; i++) { if (this[i].value === condition) { counter++; } } return counter; }; console.log(arrayObj.numBoolean(true)); console.log(arrayObj.numBoolean(false));

I'm not entirely sure what you actually want: you state a number of times that you want to count how many items have false values, yet your discussion of the code makes it sound like you only want to know if they all have false value properties.

If it's the first that you're after (the actual number of false values), you can get that by using reduce as follows:

var arrayObj = [
    { "id": 1, "value": true },
    { "id": 2, "value": false },
    { "id": 3, "value": true }
];

var numFalse = arrayObj.reduce(function(count, item) {
    return count + (item["value"] === false ? 1 : 0);
}, 0);

If it's the second (you want to know if all values are false), or you want to check if none or only some of the entries have false value entries, you can achieve those as follows:

var allFalse = numFalse == data.length,
    noneFalse = numFalse == 0,
    someFalse = numFalse > 0 && numFalse < data.length;

If you're not familiar with reduce , it works like this:

  • The second parameter to reduce (a zero) sets the initial count to zero.
  • For each item in the array, the function passed to reduced is called, with the first value being the current count and the second being the current item in the array.
  • If the item's value property is false , we add one to the count, otherwise we add zero.
  • At the end, reduce returns the final value of the count.

Do like this, use array.forEach instead of native iteration.

 var arrayObj = [{ "id": 1, "value": true }, { "id": 2, "value": false }, { "id": 3, "value": true } ]; var trueCount = 0, falseCount = 0; arrayObj.forEach(function(index) { if (index.value == true) { trueCount++; } else if (index.value == false) { falseCount++; } }); console.log('True Obj is ' + trueCount + ' False Obj is ' + falseCount);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM