Sum Number problem without using Regular Expression

Sum Number problem without using Regular Expression
0

hi, please I have problem with extracting number out of string and sum them without using regular expression.
here is my code but it is given me 44 instead of 935

function sumNumbers(str){
    return str.split('').filter(a => a.charCodeAt() <= 57).map(a => parseInt(a)).reduce((a, b) => a + b, 0);
  }
 console.log(sumNumbers('1weudh56jdnbfskjn788sdhkfbs90'))

Ahh I see, it’s because you’re separating the string in individual characters, so basically each digit is its own number. But the challenge wants you to also take in consideration 2+ digit numbers like 90, 56 and 788 (not 9 0 5 6 7 8 8 individually) hence the need for regular expressions.

It’s not that you can’t do it without it them, but it becomes more complex.

If JS’s standard library had a groupWith function you could easily group them by the <= 57 condition so you’d obtain an array of ['1', 'weudh', '56', ...etc] and filter out the ones whose parseInt result yields NaN.

But since that’s not the case, you have to iterate the whole string char by char and have a separate empty array to where you’ll push each number and checking when the character changes from being a number to a non-number.

Yes I have done that… I separated the numbers into one array, yet am still having them as single element not like [1, 56, 788, 90]
That is where the problem, kind show me the line of code to use… Please

This is the naive and semi-imperative algorithmic way of doing it:

But this is the correct way:

const sumNumbers = str => str
  .match(/\d+/g)
  .map(nStr => parseInt(nStr, 10))
  .reduce((acc, n) => acc + n, 0)
1 Like

Thank you… It is the first one I am trying to achieve I have done that of regex already… Thanks… I have seen where am getting it wrong

You can use loops for that.

  1. Create 2 empty arrays.
  2. Create empty string
  3. Go “looping” array of characters you got. Compare each member using switch case whom will return member if its char is number.
  4. Add such char to string.
  5. If currently selected member isn’t number, push string into array1.
  6. When it’s finished, take array1 which is now filled with “stringified” numbers and use it in another loop.
  7. On each member of array of stringified number use Number(member) and pushed them into second empty array.
  8. Now you got array of numbers.
    PS: Need work if your numbers are floats …
1 Like

thanks you are awesome