-2

I'm trying to take the string '27 4 2019' and output the sum of 2050. Not in a string.

So far I have split it.

let x = '27 4 2019'
console.log(x.split('').? 

I'm not sure how to add the numbers together after splitting it.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Is that supposed to represent a date? – StackSlave Apr 22 '19 at 23:31
  • Possible duplicate of [How do I split a string, breaking at a particular character?](https://stackoverflow.com/questions/96428/how-do-i-split-a-string-breaking-at-a-particular-character) – srknzl Apr 23 '19 at 21:00

4 Answers4

2

Split based on whitespace, and reduce while converting into numbers:

const str = "27 4 2019";
const output = str.split(/\s/).reduce((a, b) => a + parseInt(b), 0);
console.log(output);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You can try to:

  1. split() the String to array values using a whitespace ' ' as a separator.
  2. map() the array values from String type to Number.
  3. reduce() the array to a single value.

const s = '27 4 2019';

const out = s.split(' ').map(Number).reduce((sum, curr) => sum + curr);

console.log(out);
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

You can use a RegEx replace function to iterate through all your numerical elements and add them. +n acts as an operator to coerce the string to a number, which you know will work because we're only grabbing numerical elements from the string. This also has the added benefit of passing over the string once, where other answers may go through it several times, and it doesn't require coercion of your string to an array.

let total;
string.replace(/[0-9]/g, (n) => total = total ? total + (+n) : +n);

let x = '27 4 2019', total;
x.replace(/[0-9]/g, (n) => total = total ? total + (+n) : +n);

console.log(total);
zfrisch
  • 8,474
  • 1
  • 22
  • 34
0

Another clean solution could be to use regex to find numbers in a string and pass a supporting function to ad them up as

let x = '27 4 2019', total = 0;
x.replace(/\d+/g, (obj) => total += +obj);
console.log(total);
Saksham
  • 9,037
  • 7
  • 45
  • 73