admin管理员组

文章数量:1410674

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 acplish this?

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 acplish this?

Share Improve this question asked Dec 11, 2014 at 5:02 GRowingGRowing 4,72713 gold badges55 silver badges75 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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
}

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
}

本文标签: JQuery or JavaScriptCount how many array elements are truefalseStack Overflow