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 a
and b
are null (or undefined), the result should be [].
Are there any shorthands to avoid having to write two if
-statements?
You will push an array containing another array (i.e. [[0, 1, 2]] ). With grid. push([]. concat(row)); , you are pushing an array containing the elements contained in row (i.e. [0, 1, 2] ).
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
Using the spread operator or the concat() method is the most optimal solution. If you are sure that all inputs to merge are arrays, use spread operator . In case you are unsure, use the concat() method. You can use the push() method to merge arrays when you want to change one of the input arrays to merge.
You could make use of the ||
operator.
var a = [1, 2, 3]
var b = null
var c = [...a||[], ...b||[]]
console.log(c)
var c = [...(a || []), ...(b || [])]
This way if any array is null or undefined it will be replaced by an empty array
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With