How to avoid the emptiness error with spread?

  • 0
    How can I avoid a void error when unfolding multiple arrays?
    For example:
    const arr1 = [a, b, c]
    const arr2 = [g, g, t, y]
    const arr3 = [1, 2, 3, 4]
    const allArr = [...arr1, ...arr2, ...arr3]

    arr1 is always full, but arr2 and arr3 can be empty, or maybe one is not empty and the other is empty, but if you expand the empty space into an array, an error is thrown. How can you avoid this? Fence a bunch of checks?
    JavaScript Anonymous, Jun 15, 2019

  • 3 Answers
  • 0
    [arr1, arr2, arr3] .filter (Array.isArray) .flat ()

  • 0
    empty is it null? empty array [] can be expanded

    a1 = [2,43,5]
    a2 = []
    [...a1, ...a2]
    // (3) [2, 43, 5]

    if null / undefined, then yes fence a bunch of checks

  • 0
    const allArr = [...arr1, ...(arr2 || []), ...(arr3 || [])];

    Not that the most efficient solution, but the shortest.

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!