1

In my JS code I have two booleans, flag1 and flag2. I want to create an array ['a', 'b', 'c'] where a is included only if flag1 is true, and where b is included only if flag2 is true. What I have now is [flag1 ? 'a' : null, 'b', flag2 ? 'c' : null], but if flag1 and flag2 are false this gives me [null, 'b', null] instead of ['b'].

SOLUTION:

Here's the cleanest way I found for doing it: [...(flag1 ? ['a'] : []),'b',...(flag2 ? ['c'] : [])]

2
  • 1
    [flag1 ? 'a' : null, 'b', flag2 ? 'c' : null].filter(x=>x!==null)? Commented Mar 10, 2022 at 20:19
  • its seems duplicate of this Commented Mar 10, 2022 at 20:25

2 Answers 2

2

You could take a function which returns either the value inside an array or an empty array for spreading into an array.

const
    either = (condition, value) => condition ? [value] : [],
    getArray = (flag1, flag2) => [
        ...either(flag1, 'a'),
        ...either(flag2, 'b'),
        'c'
    ];
    
console.log(...getArray(true, true));
console.log(...getArray(false, true));
console.log(...getArray(true, false));
console.log(...getArray(false, false));

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

1 Comment

Hi Nina, thanks, this works! See my update to original question to see the way I ended up doing it.
0

Another one implementation:

const flag1 = true;
const flag2 = false;
const data = [[flag1, 'a'], [flag2, 'b'], [true, 'c']];

const result = data.flatMap(([flag, letter]) => flag ? letter : []);

console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.