2

I have 4 variables, any of them can be true or false

var a
var b
var c
var d

I would like to test 3 conditions:

  1. true if 1 out of 4 is true
  2. true if 2 out of 4 is true
  3. true if 3 out of 4 is true

I know that 0 out of 4 is true when:

a!=true && b!=true && c!=true && d!=true

and 4 out of 4 are true when:

a==true && b==true && c==true && d==true

but i cant think further.

3 Answers 3

2

You could just add the variables with boolean values. The result is a number.

value = a + b + c + d;

Then you could make a check agains the number, you want to test.

var a = false, b = true, c = true, d = true,
    value = a + b + c + d;

console.log(value);

1
  • 1
    Thanks, so simple, and worked like charm. Already tested, that was exactly what i needed.
    – Kalle
    Nov 9, 2016 at 13:54
1

When dealing with a bunch of "things" that you want to run the same test on, it usually makes sense to group them using an array.

var collection = [a, b, c, d];

You can then get an array of elements that match a test with filter:

var true_elements = collection.filter(function (value) { return (value == true); });

You can then count the results:

console.log(true_elements.length);

And do whatever tests you like

if (true_elements.length === 1) { ... }
if (true_elements.length >= 1) { ... }
// etc
1
  • That's posh. I'm not sure I like the C-idiomatic way of adding the values when it comes to Javascript.
    – Bathsheba
    Nov 9, 2016 at 13:58
1

Javascript allows you to add boolean types together. In doing this it converts the arguments to integral types with 1 for true, and 0 for false.

So you can write

a + b + c + d == 3

as your test for 3 true values and 1 false value.

Not all languages support this (e.g. Java), but Javascript, C, and C++ do. Take care with the Visual Basic type languages which use -1 as the True value.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.