Javascript reduces an array of sums with undefined values

I have this simple array with numbers:

var arr = [100,200,undefined,450,300];

I would like to use reduceto quickly sum the values ​​in this array, for example ...

var total = arr.reduce( function( s, v ){ return s += v } );

In returnI get NaN.

Is there any way to do reduceto sum values ​​in an array with undefined values? like a flag or something ... Thank you!

+4
source share
4 answers

You can use the default value for falsy values ( undefined, null, 0, ''and a few more) with logical the OR|| , for example,

v || 0

, v truthy, , , .

var arr = [100, 200, undefined, 450, 300],
    total = arr.reduce(function (s, v) { return s + (v || 0); }, 0);

console.log(total);
Hide result

BTW,

s += v
   ^ 

, s . - s . , .


  • , , , .

    • ,

      .filter(v => !isNaN(v))
      
    • .map(Number)
      
  • , , , .

    function add(a, b) {
        return a + b;
    }
    
  • Array#reduce

    initialValue ()

    , callback. , . reduce() - .

    result = array
        .filter(v => !isNaN(v))
        .map(Number)
        .reduce(add, 0);
    
+7

.

, , , .

var arr = [100,200,undefined,450,300,'string'];

var total = arr
  .filter(function(x) { return typeof(x) === 'number'}) // remove any non numbers
  .reduce(function( s, v ){ return s + Number(v) }, 0);
  
console.log(
  total
)
Hide result
+4

Just a Trojan should

var arr = [100, 200, undefined, 450, 300];

var total = arr.reduce(function(s, v) {
return v ? s += v : s += 0
});

console.log(total);
Run codeHide result
+2
source

Try with filter():

var arr = [100,200,undefined,450,300];

var total = arr.filter(i=>i != undefined).reduce( function( s, v ){ 
    return s += v;
  }, 0);
  
console.log(total)
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1693147/


All Articles