21

Given:

var a = [1, 2, 3]
var b = null

I need to:

var c = [...a, ...b]

.. but that does not work when a or b is null of course. So in this example b should just not be added, resulting in c = [1, 2, 3]. If both aand b are null (or undefined), the result should be [].

Are there any shorthands to avoid having to write two if-statements?

Efrain
  • 3,248
  • 4
  • 34
  • 61

4 Answers4

43

You could make use of the || operator.

var a = [1, 2, 3]
var b = null

var c = [...a||[], ...b||[]]

console.log(c)
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • @HondaGuy not exactly sure what you want to say with that comment. If `b` is null then it is not placed in `c` because `...b||[]` evaluates to `...[]` and this will result in no element be added to `c`. So how are your linked answers better regarding to the question of the OP? – t.niese Oct 02 '19 at 06:58
  • My mistake. I made a mistake analyzing why I had found the other solution more useful in the situation that led me here. Comment removed. Sorry. – HondaGuy Oct 03 '19 at 04:45
9
var c = [...(a || []), ...(b || [])]

This way if any array is null or undefined it will be replaced by an empty array

3

You can use filter

var a = [1, 2]
var b = null
var c = [3, null, 4]

var d = []
d.concat(a,b,c).filter(item => item !== null) // [1, 2, 3, 4]

console.log("Array", d)
0

You can validate and concat array like this using ternary operator

    const a = [1,2,3,4,5];
    const b =  null;
    const c =  [6,7,8,9];
    const final = [...a ? a :[],...b ? b : [],...c ? c : []];
    console.log(final)

Click here for code snippet

sudheer nunna
  • 1,659
  • 15
  • 17