Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate array if is not undefined

Tags:

typescript

I´m concatenate two different arrays into one,

let myarray = [...myarray1, ...myarray2];

If myarray2 is undefined how can I make this concatenation in the best way?

 if(myarray2){
         let myarray = [...myarray1, ...myarray2];
    }

This is too ugly INMHO. Could i not do something like:

let myarray = [...myarray1, ...?myarray2];
like image 979
Goldbones Avatar asked Aug 24 '26 11:08

Goldbones


1 Answers

You may use this syntax

let myarray = [...(myarray1 ?? []), ...(myarray2 ?? [])];
like image 197
np42 Avatar answered Aug 26 '26 22:08

np42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!