Reputation: 21
For instance, say I have a list of 6 boolean variables. If any 3 of these are true
, do something.
In my particular case, I'm looking at something like this:
var categoriesClicked = [];
if (category1Clicked) {
categoriesClicked.push('category1Clicked');
}
if (category2Clicked) {
categoriesClicked.push('category2Clicked');
}
...
if (categoriesClicked.length > 3) {
//User clicked at least 3 categories, do something
}
Would this be the best way?
Upvotes: 1
Views: 1206
Reputation: 68933
You can make use of an array of the values, then filter the true values to get the length.
Demo:
var valueArray = [true, true, false, true, false, false];
var trueValCount = valueArray.filter(v => v).length;
if (trueValCount === 3) {
console.log('Has 3 true value');
}
Upvotes: 2
Reputation: 6838
You can abuse the +
operator, as that converts true
to 1
and false
to 0
. (Specification)
Just add your booleans together and see if they equal to 3
let b1, b2, b3, b4, b5, b6;
b1 = b2 = b3 = true;
b4 = b5 = b6 = false;
console.log(b1 + b2 + b3 + b4 + b5 + b6 === 3);
Upvotes: 3
Reputation: 29
you can keep track of count using numeric value. unnecessary creating map would not be suggestible. like
var count=0;
if(category1Clicked){
count = count+1;
}
if(category2Clicked){
count = count+1;
}
...
if(count >= 3){
//User clicked at least 3 categories, do something
}
Upvotes: 0