user3064626
user3064626

Reputation: 361

Javascript: Compare three booleans and return all true booleans

I have a method getPreferredfood(). It gets three boolean values that represent different food items. Which ever of them are true, you return those.

getPreferredFood: function (){
 var item 1; 
 var item2 ;
 var item3;

 //comparison?

 return "Preferred food is " (whichever item was true)
 }

I'm not sure how to return the the item that are true.

Upvotes: 1

Views: 1609

Answers (4)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93461

I recommend to attach your variable to namespace (example: api) :

     var api={};

    api.vegan= true
    api.non_veg= false
    api.veg = false;

Then , what you need is to loop through properties of this namespace and filter true ones .

'Person prefers  '+Object.keys(api).filter((ky)=>api[ky]).join(',');

If you cannot add it to namespace ,the default namespace is window & you need then to have a whitelist to loop on .

DEMO

var api={};
api.vegan= true;
api.non_veg= false;
api.veg = false;
console.log(
'Person prefers '+ Object.keys(api).filter((ky)=>api[ky]).join(',')
  )

Upvotes: 0

Richard Walton
Richard Walton

Reputation: 4785

var preferenceValues = {
   'vegan': true,
   'non-veg': false,
   'veg': false
}

function getPreferences(preferenceValues) {
   var preferences = [];

   for(type in preferenceValues) {
      if (preferenceValues[type]) {
          preferences.push(type);
      }
   }

   return 'Person prefers ' + preferences.join(', ') + ' food';
}


console.log(getPreferences(preferenceValues))

Upvotes: 1

Halcyon
Halcyon

Reputation: 57703

It looks like you want to use the variable name as part of a string output. That's not usually how you want to do things.

Consider doing this instead:

var tags = {
    "vegan": true,
    "non-veg": false,
    "veg": false
};

var true_tags = [];
for (var tag in tags) {
    if (tags[tag] === true) {
        true_tags.push(tag);
    }
}

console.log(true_tags); // will print [ "vegan" ]

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816960

Store the values in an object / map:

var options = {
  a: true,
  b: true,
  c: false,
};

Use Object.keys to get the names and use .filter on that array to filter out the ones that are false:

Object.keys(options).filter(function(x) {
  return options[x];
});
// ['a', 'b']

Upvotes: 3

Related Questions