How to Define an Array with Conditional Elements in JavaScript?
Last Updated :
14 Aug, 2024
Sometime we may need to define an array with elements that depend on certain conditions. Such situation may occur when we have to dynamically generate arrays based on runtime logic such as including or excluding elements based on specific criteria. In this article, we'll explore various ways to define arrays with conditional elements in JavaScript.
Following are the different approaches to defining an array with conditional elements in JavaScript:
Using the Ternary Operator
In this approach, we are using the ternary operator which has a compact syntax that evaluates a condition and returns one of two values depending on whether the condition is true or false. When defining an array we use the ternary operator to include or exclude elements based on a condition. If the condition is true, value1 is included in the array otherwise value2 is included.
Syntax:
let array = [condition ? value1 : value2];
Example: This example demonstrates using the ternary operator to include elements in an array based on a simple condition.
JavaScript
let isUserLoggedIn = true;
let userRoles = ["guest", isUserLoggedIn ? "user" : "visitor"];
console.log(userRoles);
Output[ 'guest', 'user' ]
Using Spread Operator with Conditional Logic
In this approach we are using the spread operator (...). It expands an iterable (like an array) into individual elements. By combining it with conditional logic, we can spread elements into an array only when the condition is met.
Syntax:
let array = [value1, ...(condition ? [value2] : []), value3];
Example: This example demonstrates using the spread operator to build an array conditionally.
JavaScript
let isAdmin = true;
let features = [
"basic",
...isAdmin ? ["admin-panel"] : [],
"User"
];
console.log(features);
Output[ 'basic', 'admin-panel', 'User' ]
Using filter() Method
For more complex conditions we can use the filter() method it can be used to include elements based on a function's return value. This is particularly useful when dealing with arrays of objects or more intricate logic.
Syntax:
let array = values.filter(conditionFunction);
Example: This example demonstrates how to use filter() to create a new array that only includes even numbers from the original array.
JavaScript
let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
Similar Reads
How to define custom Array methods in JavaScript? JavaScript arrays are versatile data structures used to store collections of items. When you want to iterate through the elements of an array, it's common to use loops like for, for...of, or forEach. However, there's a nuance when it comes to iterating through arrays that have additional properties
2 min read
How to add elements to an existing array dynamically in JavaScript ? An array is a JavaScript object that can hold multiple values at a time, irrespective of the data type. In this article, we will see how to add new elements to an existing array dynamically in Javascript. We will discuss two methods in this article i.e. push() method and dynamically adding an elemen
4 min read
How to Declare an Array in JavaScript? Array in JavaScript are used to store multiple values in a single variable. It can contain any type of data like - numbers, strings, booleans, objects, etc. There are varous ways to declare arrays in JavaScript, but the simplest and common is Array Litral Notations. Using Array Literal NotationThe b
3 min read
How to Filter an Array in JavaScript ? The array.filter() method is used to filter array in JavaScript. The filter() method iterates and check every element for the given condition and returns a new array with the filtered output.Syntaxconst filteredArray = array.filter( callbackFunction ( element [, index [, array]])[, thisArg]);Note: I
2 min read
How to Declare Two Dimensional Empty Array in JavaScript ? In this article, we are going to learn about Declare two-dimensional empty array by using JavaScript. A two-dimensional array is also known as a 2D array. It is a data structure in JavaScript that can hold values in rows and columns form. It is an array of arrays. Each element in a 2D array is acces
3 min read
How to Check if an Element Exists in an Array in JavaScript? Given an array, the task is to check whether an element present in an array or not in JavaScript. If the element present in array, then it returns true, otherwise returns false.The indexOf() method returns the index of first occurance of element in an array, and -1 of the element not found in array.
2 min read