Home > Net >  Summing up only numbers in an argument
Summing up only numbers in an argument

Time:09-15

How to sum up only numbers that is merge with alphabets inside an argument in javascript

function getSum(){}
 getSum("1ha","22rr","33y",44) => the output will be like this 100

I have tried this but this is not the expected result

 function getSum () {
   return Array.from(arguments).reduce((sum, value) => {
   if (Array.isArray(value)) {
     sum  = getSum.apply(this, value)
   } else {
   sum  = Number(value)
 }

  return sum
 }, 0)
}

Can someone help me with this please!

CodePudding user response:

We can try a reduction after using match() on each argument:

function getSum() {
    return Array.from(arguments).map(x => x.toString().match(/\d /))
                                .reduce((partialSum, a) => partialSum   parseInt(a), 0);
}

var output = getSum("1ha", "22rr", "33y", 44);
console.log(output);

  • Related