Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Summing numbers present in a string separated by spaces using JavaScript
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.
Problem
Given a string containing numbers separated by spaces, we need to:
- Split the string into individual number strings
- Convert each string to a number
- Calculate the sum of all numbers
Method 1: Using split() and reduce()
const str = '1 5 12 76 2';
const sumStringNumbers = (str = '') => {
const sum = str
.split(' ')
.map(Number)
.reduce((acc, val) => acc + val, 0);
return sum;
};
console.log(sumStringNumbers(str));
96
Method 2: Using for...of Loop
const str = '1 5 12 76 2';
const sumStringNumbers = (str = '') => {
let sum = 0;
const numbers = str.split(' ');
for (const num of numbers) {
sum += Number(num);
}
return sum;
};
console.log(sumStringNumbers(str));
96
Method 3: Using parseInt() with forEach()
const str = '1 5 12 76 2';
const sumStringNumbers = (str = '') => {
let sum = 0;
str.split(' ').forEach(numStr => {
sum += parseInt(numStr, 10);
});
return sum;
};
console.log(sumStringNumbers(str));
96
How It Works
The solution breaks down into these steps:
-
split(' ')converts the string into an array of number strings -
map(Number)orparseInt()converts each string to a number -
reduce()or a loop accumulates the sum
Comparison
| Method | Readability | Performance | Lines of Code |
|---|---|---|---|
| split() + reduce() | High | Good | Minimal |
| for...of loop | Medium | Best | More |
| forEach() | Medium | Good | Medium |
Edge Cases
// Empty string
console.log(sumStringNumbers('')); // 0
// Single number
console.log(sumStringNumbers('42')); // 42
// Negative numbers
console.log(sumStringNumbers('-5 10 -3')); // 2
0 42 2
Conclusion
The split() and reduce() approach provides the most concise solution for summing space-separated numbers in a string. Choose the for...of loop for better performance with large datasets.
Advertisements
