Conditionally Define or Add Elements to a JavaScript Array

Robin
Updated on April 21, 2023

You can easily define an array in JavaScript with conditional items or you can also add new elements to the array based on certain conditions. JavaScript has different techniques for that.

In this blog post, you will learn the multiple methods for conditionally defining or adding elements to a JavaScript array.

These are the 4 techniques for defining or adding elements to an array in JavaScript:

  • Using Spread Operator.
  • Using Ternary Operator.
  • Using if Statement with push() Method.
  • Using concat() Method to Join Arrays.

Let's learn each of these methods with examples.

Spread Operator: Define JavaScript Array with Conditional Items

You can use the spread operator to conditionally add elements to an array based on a ternary expression. It allows you to concatenate multiple arrays into a single array.

While defining an array you spread another array based on a condition. If the condition is true then your array will have all the elements from the second array.

          const value = 6

const colors = [
    'Red',
    'Green',
    'Yellow',
    ...(value <= 10 ? ['Blue', 'Orange', 'Purple'] : []),
]

console.log(colors)
// [ 'Red', 'Green', 'Yellow', 'Blue', 'Orange', 'Purple' ]
        

In this case, I am concatenating the colors array with an array based on the value variable. I am using the ternary operator to evaluate the condition.

If the condition is true, the ternary operator returns an array containing the values Blue, Orange, and Purple. Otherwise, it will return an empty array.

Finally, I am spreading the returned array from the condition inside the colors array.

Also Read: Store and Get JavaScript Arrays in localStorage [Many Ways]


Ternary Operator: Add Elements to an Array Conditionally

Instead of adding a whole array, you can conditionally add a single element to an array in JavaScript. For that, all you need to use is a ternary operator.

          const num = 12

const colors = ['Red', 'Green', 'Yellow', value <= 10 ? 'Orange' : 'Blue']

console.log(colors)
// [ 'Red', 'Green', 'Yellow', 'Blue' ]
        

Here I have a colors array with 3 items. I am adding the fourth element conditionally. If the value of num is less than or equal to 10, it will add Orange otherwise Blue to the array.

This condition adds one item out of two. But it is also possible to add one item conditionally.

          const num = 12

const colors = ['Red', 'Green', 'Yellow', value <= 10 ? 'Orange' : null].filter(Boolean)

console.log(colors)
// [ 'Red', 'Green', 'Yellow' ]
        

In this example, I am using the same condition. If the condition is true, it will add Orange to the array. But if it is false, it will add null.

To remove null from your array call filter() method with the Boolean constructor function. It will remove all the false values from your array.

But if you want to remove only null values, use this with the filter() method.

          const num = 12

const colors = ['Red', 'Green', 'Yellow', value <= 10 ? 'Orange' : null].filter(
    (x) => x !== null
)

console.log(colors)
// [ 'Red', 'Green', 'Yellow']
        

Also Read: Tricks to Loop Through an Array of Objects in JavaScript


Conditionally Push Elements to a JavaScript Array

You can push elements to an array using the if statement based on multiple conditions. You will add a different item for a different condition.

          const num = 13

const colors = ['Red', 'Green', 'Yellow']

if (num <= 10) {
    colors.push('Orange')
} else if (num > 10 && num <= 20) {
    colors.push('Blue')
} else {
    colors.push('Purple')
}

console.log(colors)
// [ 'Red', 'Green', 'Yellow', 'Blue' ]
        

Here, if the value of num is less than or equal to 10, it will push Orange to the colors array. But if the value is greater than 10 and less than or equal to 20, it will push Blue.

If none of those conditions are true, it will push Purple to the array. As you can see, I am checking multiple conditions and adding different elements.

There is a shortcut way to check one condition and add one item if that condition is true.

          const num = 7

const colors = ['Red', 'Green', 'Yellow']

numb <= 10 && colors.push('Orange')

console.log(colors)
// [ 'Red', 'Green', 'Yellow', 'Orange' ]
        

If the value of num is less than or equal to 10, it will push Orange to the colors array. Otherwise, it won't do anything.

Also Read: 6+ Ways to Find an Object in an Array of Objects Using JavaScript


Join Multiple Arrays Conditionally Using concat() Method

The concat() method combines two or more arrays in JavaScript. You can also join multiple arrays conditionally using this method.

You can use the ternary operator for providing an array to this method based on a condition.

          const num = 8

const colors1 = ['Red', 'Green', 'Yellow']
const colors2 = ['Blue', 'Orange', 'Purple']

const colors = colors1.concat(num <= 10 ? colors2 : [])

console.log(colors)
// [ 'Red', 'Green', 'Yellow', 'Blue', 'Orange', 'Purple' ]
        

Here I have two arrays colors1 and colors2. I want to merge these two arrays if the num value is less than or equal to 10. I am checking this condition inside the concat() method.

If the condition is true, it will concatenate the colors1 and colors2 arrays. Otherwise, it will concatenate colors1 and an empty array.

Also Read: Remove Duplicates From a JavaScript Array Like a Pro (Easy)


Conclusion

One of the main techniques to concatenate arrays conditionally is using the spread syntax and ternary operator. You can use this technique to add elements based on a specific condition.

There are also other ways to achieve this. I have discussed 4 different methods in this blog post. You can join multiple arrays together or add a single item to an array using concat() or push() methods.

Apply any of these techniques to your code for different situations to define a JavaScript array with conditional elements.

Related Posts