Create an array with conditional elements
Written byPhuoc Nguyen
Category
Tip
Tags
JavaScript
Created
12 Mar, 2021
There are a few ways to initialize an array with conditional elements.
#Using the `push`
function
const arr = ['foo', 'bar'];
if (condition) {
arr.push('fuzz');
}
We can use the short-circuits conditionals to make it shorter:
condition && arr.push('fuzz');
#Using the `concat`
function
const arr = ['foo', 'bar'].concat(condition ? 'fuzz' : []);
The
`push`
and `concat`
functions only work if we want to insert the elements at the end of the array.#Filtering the falsy values
const arr = ['foo', condition ? 'fuzz' : undefined, 'bar'].filter(Boolean);
The array always inserts new item which can be the new element or
`undefined`
depending on whether or not the condition matches.
At the end, the `undefined`
items are removed from the array.This approach allows us to insert element at any position, however we have to be careful with removing the falsy values from the array because the original array can contains the falsy items.
#Tip: using the spread operator
By using the spread operator (
`...`
), we can create an array with a single expression as following:const arr = ['foo', ...(condition ? ['fuzz'] : []), 'bar'];
The following code demonstrates a simple use case. It adds a product to the cart on an ecommerce website.
To do that, we have to check if the
`products`
property exists on the `cart`
object first. If not, it will create an empty `products`
. The conditional elements are the current `products`
.if (!cart['products']) {
cart['products'] = [];
}
cart['products'].push(product);
// Better version
cart['products'] = [...(cart['products'] || []), product];
Do you want to see one more advanced example? The function below uses the spread and comma operator to group an array of objects by a key:
const groupBy = (arr, key) => arr.reduce((a, i) => ((a[i[key]] = [...(a[i[key]] || []), i]), a), {});
#See also
Questions? 🙋
Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.
Recent posts ⚡
Copy the content of an element to your clipboard
01 Oct, 2023
Make a text area fit its content automatically
30 Sep, 2023
Quickly insert alternate characters while typing
30 Sep, 2023
Zebra-like background
30 Sep, 2023
Add autocomplete to your text area
28 Sep, 2023
Linear scale of a number between two ranges
28 Sep, 2023
Highlight the current line in a text area
27 Sep, 2023
Create your own custom cursor in a text area
27 Sep, 2023
Mirror a text area for improving user experience
26 Sep, 2023
Display the line numbers in a text area
24 Sep, 2023
Select a given line in a text area
24 Sep, 2023
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn