Summing numbers present in a string separated by spaces using JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 20-Apr-2021 09:09:37
Advertisements