How to define an array with conditional elements?

后端 未结 10 1660
半阙折子戏
半阙折子戏 2020-12-07 14:01

how can i define conditional array elements? i want to do something like this:

const cond = true;
const myArr = [\"foo\", cond && \"bar\"];


        
相关标签:
10条回答
  • 2020-12-07 14:06

    You can spread an array inside of an array, in order to keep items array clean, when the condition is 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.

    If the condition is true, then it returns ['bar'], otherwise an empty array [].

    After that we spread out ... the resulted array (from the ternary operation) and the array's items are pushed to the parent array.

    If there aren't any array items (when the ternary check is false), then nothing will be pushed, which is our goal.


    In other answer I explained the same idea, but for objects. You can check it too here.

    0 讨论(0)
  • 2020-12-07 14:06
    const cond = false;
    const myArr = ["foo", cond ? "bar" : null].filter(Boolean);
    
    console.log(myArr)
    

    Will result in ["foo"]

    0 讨论(0)
  • 2020-12-07 14:09

    Alternative approach: Pre-Filter populate instead of post filtering:

    const populate = function(...values) {
        return values.filter(function(el) {
            return el !== false
        });
    };
    
    console.log(populate("foo", true && "bar", false && "baz"))
    

    Returns

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

    I know that does not solve the shorthand notation (since it won't work no matter what you try) but it comes close to that.

    0 讨论(0)
  • 2020-12-07 14:14

    If you really want to keep it as a one liner, you could use:

    const cond = true;
    const myArr = ["foo"].concat(cond ? ["bar"] : []);
    
    0 讨论(0)
  • 2020-12-07 14:16

    if you use Array.push

    You can do follow

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

    Result is ["1"]

    or

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

    Result is ["1","2"]

    0 讨论(0)
  • 2020-12-07 14:18

    I'd do this

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

    Note that this will also remove falsy values, such as empty strings.

    0 讨论(0)
提交回复
热议问题