In Javascript, how to avoid NaN when adding arrays

I am trying to add the values โ€‹โ€‹of two arrays in javascript, for example. [1,2,1] + [3,2,3,4]

The answer should be 4,4,4,4, but I either get 4,4,4 or 4,4,4, NaN if I change the length of the 1st array to 4.

I know that the fourth number should be in the 1st array, but I cannot figure out how to say javascript to make it 0, and not undefined if there is no number.

+7
javascript arrays nan
source share
4 answers

Use isNaN to make sure that the value is not evaluated in NaN in arithmetic operations.

This will safely add two numbers, so if one of them is not a number, it will be replaced by 0.

 var c = (isNaN(a) ? 0 : a) + (isNaN(b) ? 0 : b); 

If you suspect that either a or b may be a string instead of a number ( "2" instead of 2 ), you need to convert it to a number before adding. You can use Unary + for this.

 var c = (isNaN(a) ? 0 : +a) + (isNaN(b) ? 0 : +b); 
+9
source share
 (array1[3] || 0) + (array2[3] || 0) 
+6
source share
 var a = [ 1, 2, 3, 4, 5 ]; var b = [ 2 , 3]; var c = []; var maxi = Math.max(a.length, b.length); for (var i = 0; i < maxi; i++) { c.push( (a[i] || 0) + (b[i] || 0) ); } 
+1
source share
 [1,2,3] + [3,2,1] 

In the above example, JavaScript will still convert arrays to strings, so the result is:

 1,2,33,2,1 
0
source share

All Articles