Method 1: Ternary Operators and Filter Method
This method takes advantage of JavaScript's ternary operators and the filter method of arrays. An element is added to the array conditionally using a ternary operator and the resulting array is filtered to exclude any null values.
Here's a sample code snippet:
_10let item1 = 'value1'_10let item2 = 'value2'_10let item3 = 'value3'_10_10let condition1 = item1 && item2_10let condition2 = item2 && item3_10_10let array = [condition1 ? item1 : null, item2, condition2 ? item3 : null].filter(_10 (item) => item !== null,_10)
Method 2: Spread Syntax
This approach uses JavaScript's spread syntax (...
).
It's more concise and doesn't require additional filtering.
If the condition is true
, an array item gets included.
If the condition is false
, an empty array gets spread, which effectively includes no extra elements.
Here's a sample code snippet:
_10let item1 = 'value1'_10let item2 = 'value2'_10let item3 = 'value3'_10_10let condition1 = item1 && item2_10let condition2 = item2 && item3_10_10let array = [...(condition1 ? [item1] : []), item2, ...(condition2 ? [item3] : [])]