How to define an array with conditional elements?

I'd do this

[
  true && 'one',
  false && 'two',
  1 === 1 && 'three',
  1 + 1 === 9 && 'four'
].filter(Boolean) // ['one', 'three']

Note that this will also remove falsy values, such as empty strings.


You can spread an array inside of an array, in order to keep items array clean, when the condition is false.

Here's how you can do it:

// Will result in ['foo', 'bar']
const items = [
  'foo',
  ... true ? ['bar'] : [],
  ... false ? ['falsy'] : [],
]

console.log(items)

Explanations:

As you can see the ternary operator always returns an array.

If the condition is true, then it returns ['bar'], otherwise an empty array [].

After that we spread out ... the resulted array (from the ternary operation) and the array's items are pushed to the parent array.

If there aren't any array items (when the ternary check is false), then nothing will be pushed, which is our goal.


In other answer I explained the same idea, but for objects. You can check it too here.