How can I define elements of a conditional array? I want to do something like this:
const cond = true; const myArr = ["foo", cond && "bar"];
this works as expected: ["foo", "bar"]
["foo", "bar"]
But if I install condin false, I get the following result:["foo", false]
cond
false
["foo", false]
How can I define an array with a conditional element?
You can distribute the array inside the array to keep the array of elements clean when the condition false.
Here's how you can do it :
// Will result in ['foo', 'bar'] const items = [ 'foo', ... true ? ['bar'] : [], ... false ? ['falsy'] : [], ] console.log(items)
Explanations :
As you can see, the ternary operator always returns an array.
true, ['bar'], - [].
true
['bar']
[]
... ( ) .
...
( false), , .
, . .
[ true && 'one', false && 'two', 1 === 1 && 'three', 1 + 1 === 9 && 'four' ].filter(Boolean) // ['one', 'three']
, , .
, :
if(cond) { myArr.push("bar"); }
const cond = true; const myArr = ["foo"].concat(cond ? ["bar"] : []);
, push:
push
const cond = true; const myArr = ["foo"]; if (cond) myArr.push("bar");
- :
const cond = true; const myArr = ["foo", cond ? "bar" : null]; myArr = myArr.filter((item) => item !== null);
, , , Javascript.
- if.
if (myCond) arr.push(element);
filter, , , , , " , ", - , , , ( , , ).
filter
var arr = ["a", cond && "bar"]; arr.filter( e => e)
, .
ES6;
arr = [ "Hello", "World", ...(true && ["conditional element"]) ]
: :
const populate = function(...values) { return values.filter(function(el) { return el !== false }); }; console.log(populate("foo", true && "bar", false && "baz"))
(2) ["foo", "bar"]
, ( , ), .
, https://medium.com/@payelroyburman14/if-you-are-new-to-es6-the-following-article-might-be-helpful-4b7d093e0079
es6,
let array = [ "bike", "car", name === "van"? "van": null, "bus", "truck", ].filter(Boolean);
This array will contain the value "van" only if name is equal to "van", otherwise it will be discarded.
if you use Array.push
Array.push
You can follow
var a = ["1"] a.push(... !true ? ["2"] : [])
Result ["1"]
["1"]
or
var a = ["1"] a.push(... true ? ["2"] : [])
Result - ["1","2"]
["1","2"]