javascript - How to sum only numbers in array with different value types with reduce? -
i need sum numbers of array reduce don’t know how.
this code , attempt:
let arr = [1,2,3,4,6,true,"dio brando", false,10,"yare yare"];  let sum = arr.reduce((a.b)=> typeof.a =="number" && typeof.b =="number"? a+b :false) console.log(sum); 
you need make following changes:
- (a.b) should (a, b), it's function parameters
- there's no such thing "typeof.a", should "typeof a"
i've rewritten more helpful variable names explain what's going on in reduce.
const arr = [1,2,3,4,6,true,"dio brando", false,10,"yare yare"];    const sum = arr.reduce( (sumsofar, nextvalue) => {     if ( typeof nextvalue === "number" && isfinite(nextvalue) ) {        return sumsofar + nextvalue;     }     //skip otherwise     return sumsofar;  }, 0); //sum starting 0      console.log(sum);
Comments
Post a Comment