-3

Any help with the below. The function should take any string with a jumble of letters and numbers. It should add together all the numbers that appear in the string and return the total.

E.g. 'foo5bar6cat1' => 12 'foo98cat' => 17

I have tried the following but no luck.

 function sumDigitsFromString (str) {
    let arr = str.split('');
    arr = arr.reduce(function(a, b) {
       return Number('0') + Number('a');
     }, 0);
     return arr;
    }
Dhana
  • 1,618
  • 4
  • 23
  • 39
Vuweveka
  • 9
  • 3
  • 3
    The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Oct 25 '18 at 00:00
  • 1
    Your function isn't using `a` or `b`. How do you possibly expect it to work? It seems like you posted code that doesn't even try to solve the problem. – Barmar Oct 25 '18 at 00:05
  • sorry edited my initial post to include complete code – Vuweveka Oct 25 '18 at 00:07
  • How is that code supposed to do what you're trying to do? `Number('0')` is always `0`, and `Number('a')` is always `NaN`. `0 + NaN` is always `NaN`. It's not making any attempt to add the numbers in the array. – Barmar Oct 25 '18 at 00:27

2 Answers2

0

You can split that string, and use the function reduce to sum all the numbers.

let add = s => s.split('').reduce((a, c) => a + (isNaN(+c) ? 0 : +c), 0);

console.log(add('foo5bar6cat1'));
console.log(add('foo98cat'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
0

You can use match to grab the digits from the string and reduce over that.

function sumDigitsFromString(str) {
  return str.match(/\d/g).reduce((n, c) => n + +c, 0);
}

const out = sumDigitsFromString('foo5bar6cat1');
const out2 = sumDigitsFromString('foo98cat');
console.log(out, out2);
Andy
  • 61,948
  • 13
  • 68
  • 95