GRowing
GRowing

Reputation: 4717

JQuery or JavaScript - Count how many array elements are true/false

I have an instance where arrays of potentially different length can look like this...

Array [ true, false, false, true ]

Or

Array [ true, true, true, false, true ]

Or

Array [ true, true, true ]

I need to iterate through an array and ONLY trigger a new event if there is ONE instance of "false".

Out of sample arrays I presented,, this one wold be the only one that is valid

Array [ true, true, true, false, true ]

What would be the least elaborate way to accomplish this?

Upvotes: 1

Views: 1446

Answers (2)

Kevin Ji
Kevin Ji

Reputation: 10499

Amit Joki already has a working answer, but I'd just like to share another solution using reduce:

var count = arr.reduce(function(prevVal, currVal) {
    return prevVal + (!currVal ? 1 : 0);
}, 0);

if (count === 1) {
    // Do something
}

Upvotes: 4

Amit Joki
Amit Joki

Reputation: 59262

You could do it by using Array.filter

var arr = [ true, true, true, false, true ];
if(arr.filter(function(b){ return !b; }).length == 1){
   // trigger the event
}

The above filters to just contain Array of false and then we check if the length of that Array is 1

Another creative way of doing this might be using replace and indexOf, where you're just replacing the first occurrence of false in a String formed by joining the arr and checking if there are still any false in the string and negate it with ! operator to achieve the results.

if(!(arr.join("").replace("false","").indexOf("false") > -1)){
  // trigger
}

Upvotes: 7

Related Questions