DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#21 - Sum of integers in string CodeWars Kata (7 kyu)

Instructions

Your task in this kata is to implement a function that calculates the sum of the integers inside a string.

For example:

Input --> "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog"
Output --> 3635.


My solution:

function sumOfIntegersInString(s){
  return s
    .split(/([^0-9])/g)
    .map(x => parseInt(x) )
    .filter(Boolean)
    .reduce((acc,el)=> acc+el,0)
}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I splitted the string using a regex that matches the elements that are not numbers, so everytime an element is not a number it'll split.

Input --> 'h3ll0w0rld'

Output --> ['', 'h', '3', '1', '', 'l', '0', 'w', '0', 'r', '', 'l', '', 'd', '']


After that I converted every string element in the array to a number

Input --> ['', 'h', '3', '1', '', 'l', '0', 'w', '0', 'r', '', 'l', '', 'd', '']

Output --> [NaN, NaN, 3, NaN, NaN, NaN, 0, NaN, 0, NaN, NaN, NaN, NaN, NaN, NaN]


After that I filtered the array and I used Boolean so I would get every falsy element removed

Input --> [NaN, NaN, 3, 1, NaN, NaN, 0, NaN, 0, NaN, NaN, NaN, NaN, NaN, NaN]

Output --> [3,1]


At the end I just used .reduce() so I could sum all of the numbers left in the array

Input --> [3,1]

Output --> 4


What do you think about this solution? 👇🤔

My Github
My twitter
Solve this Kata

Discussion (0)