Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  175] [ 1]  / answers: 1 / hits: 22401  / 9 Years ago, thu, august 20, 2015, 12:00:00

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

More From » arrays

 Answers
19

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;

[#65356] Tuesday, August 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leandraannabellar

Total Points: 255
Total Questions: 89
Total Answers: 89

Location: England
Member since Sun, May 21, 2023
1 Year ago
;