0

Suppose I have:

const apple = true
const pear = false
const coconut = true

I would like to have:

const activeFruits = ['apple', 'coconut']

How can I do something like this? This is what I've tried:

const activeFruits = [
 apple ? 'apple' : '',
 pear ? 'pear' : '',
 coconut ? 'coconut' : '',
]

Then I have to filter out the empty string.

It works but doesn't seem to be to me the smartest way. Is there a better way?

3 Answers 3

1

One idea to have a dynamic way will be to have an object that contains your variables:

const fruits = {
  apple: true,
  pear: false,
  coconut: true
};

const activeFruit = Object.keys(fruits).filter(key => !!fruits[key]);

console.log(activeFruit)

Sign up to request clarification or add additional context in comments.

Comments

0

Not sure if this is smarter or the smartest, but this is a different approach

You could wrap all of the fruits into an object, transform that object into key-value pairs (using Object.entries()), filter pairs which have value of true, and then map the pairs to get the keys

const apple = true
const pear = false
const coconut = true

const obj = {
  apple,
  pear,
  coconut
}

const activeFruits = Object.entries(obj)
  .filter(([_, value]) => value === true)
  .map(([key, _]) => key)

console.log(activeFruits)

Comments

0

To answer your question, I would do it like this:

if (apple) {
    activeFruits.push('apple');
}

if (pear) {
    activeFruits.push('pear');
}

if (coconut) {
    activeFruits.push('coconut');
}

However, I would question the initial data structure you have and (if possible) change it to:

const fruits = {
    apple: true,
    pear: false,
    coconut: true
};

Then get the answer like this:

const activeFruits = Object.keys(fruits).filter(key => !!fruits[key]);

Comments

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.