# Sum Number problem without using Regular Expression

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