Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Null-Safe Array Concat

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?

like image 708
Efrain Avatar asked Aug 23 '18 18:08

Efrain


People also ask

Can we concat empty array in JavaScript?

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] ).

How to concat to array in js?

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.

Does concat return a new array?

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.

How to merge two object arrays in JavaScript?

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.


3 Answers

You could make use of the || operator.

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

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

console.log(c)
like image 138
t.niese Avatar answered Sep 22 '22 20:09

t.niese


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

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

like image 24
Guy who types fast Avatar answered Sep 24 '22 20:09

Guy who types fast


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)
like image 31
Kỳ Phạm HỒng Avatar answered Sep 25 '22 20:09

Kỳ Phạm HỒng