Summing numbers present in a string separated by spaces using JavaScript


Problem

We are required to write a JavaScript function that takes in a string which has integers inside it separated by spaces.

The task of our function is to convert each integer in the string into an integer and return their sum.

Example

Following is the code −

 Live Demo

const str = '1 5 12 76 2';
const sumStringNumbers = (str = '') => {
   const findSum = (arr = []) => {
      const sum = arr.reduce((acc, val) => acc + val);
      return sum;
   };
   let sum = 0;
   const arr = str
      .split(' ')
      .map(Number);
   sum = findSum(arr);
   return sum;
};
console.log(sumStringNumbers(str));

Output

96

Updated on: 20-Apr-2021

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements