1

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?

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

I will test this in a minute. It looks like it will do well for what I need. Thanks!
@GRowing sure. Glad to have helped you.
4

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
}

1 Comment

This is a great suggestion too. Thanks for pitching in :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.