Skip to main content

Condition Arrays

In JavaScript, working with arrays and conditions can sometimes become verbose and cluttered.

––– views

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:


_10
let item1 = 'value1'
_10
let item2 = 'value2'
_10
let item3 = 'value3'
_10
_10
let condition1 = item1 && item2
_10
let condition2 = item2 && item3
_10
_10
let 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:


_10
let item1 = 'value1'
_10
let item2 = 'value2'
_10
let item3 = 'value3'
_10
_10
let condition1 = item1 && item2
_10
let condition2 = item2 && item3
_10
_10
let array = [...(condition1 ? [item1] : []), item2, ...(condition2 ? [item3] : [])]