-
Notifications
You must be signed in to change notification settings - Fork 0
/
10oct22ExtractNum.js
28 lines (18 loc) · 955 Bytes
/
10oct22ExtractNum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Given a random string consisting of numbers, letters, symbols, you need to sum up the numbers in the string.
Note:
Consecutive integers should be treated as a single number. eg, 2015 should be treated as a single number 2015, NOT four numbers
All the numbers should be treaded as positive integer. eg, 11-14 should be treated as two numbers 11 and 14. Same as 3.14, should be treated as two numbers 3 and 14
If no number was given in the string, it should return 0
Example:
str = "In 2015, I want to know how much does iPhone 6+ cost?"
The numbers are 2015, 6
Sum is 2021.
function sumFromString(str){
// string, has numbers
// return sum of numbers
// "In 2015, I want to know how much does iPhone 6+ cost?" should
// return 2021
//take the numbers out of string, add them
return (str.match(/\d+/g)|| []).map(Number).reduce((a,b)=> a+b, 0)
}
let sumFromString = (str) => str.split(/[^0-9]+/).reduce((a, b) => +a + +b, 0);