how can i define conditional array elements? i want to do something like this:
const cond = true;
const myArr = [\"foo\", cond && \"bar\"];
You don't have so many options other than using push
:
const cond = true;
const myArr = ["foo"];
if (cond) myArr.push("bar");
Another idea is potentially adding null's and filtering them out:
const cond = true;
const myArr = ["foo", cond ? "bar" : null];
myArr = myArr.filter((item) => item !== null);
if you are using es6, I would suggest
let array = [
"bike",
"car",
name === "van" ? "van" : null,
"bus",
"truck",
].filter(Boolean);
This array will only contain value "van" if name equals "van", otherwise it will be discarded.
You can try with a simple if :
if(cond) {
myArr.push("bar");
}
There's a few different ways, but the way you're doing it won't really work for Javascript.
The easiest solution would be to just have an if statement.
if (myCond) arr.push(element);
There's also filter
, but I don't think that's what you want here at all, since you seem to be going for "Add this one thing, if this one condition is true" rather than checking everything against some condition. Although, if you want to get really freaky, you can do this (would not recommend, but it's cool that you can).
var arr = ["a", cond && "bar"];
arr.filter( e => e)
Basically it will just filter out all the non true values.