How to define an array with conditional elements?

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"]

But if I install condin false, I get the following result:["foo", false]

How can I define an array with a conditional element?

+45
source share
11 answers

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)
Run codeHide result

Explanations :

As you can see, the ternary operator always returns an array.

true, ['bar'], - [].

... ( ) .

( false), , .


, . .

+95

[
  true && 'one',
  false && 'two',
  1 === 1 && 'three',
  1 + 1 === 9 && 'four'
].filter(Boolean) // ['one', 'three']

, , .

+10

, :

if(cond) {
    myArr.push("bar");
}
+4

, :

const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);
+4

, 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);
+3

, , , Javascript.

- if.

if (myCond) arr.push(element);

filter, , , , , " , ", - , , , ( , , ).

var arr = ["a", cond && "bar"];
arr.filter( e => e)

, .

+1

ES6;

arr = [
  "Hello",
  "World",
  ...(true && ["conditional element"])
]
+1

: :

const populate = function(...values) {
    return values.filter(function(el) {
        return el !== false
    });
};

console.log(populate("foo", true && "bar", false && "baz"))

(2) ["foo", "bar"]

, ( , ), .

0

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.

0
source

if you use Array.push

You can follow

var a = ["1"]
a.push(... !true ? ["2"] : [])

Result ["1"]

or

var a = ["1"]
a.push(... true ? ["2"] : [])

Result - ["1","2"]

-1
source

All Articles