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 array of string numbers using JavaScript
Problem
We are required to write a JavaScript function that takes in an array that contains integers and string numbers.
Our function should sum all the integers and string numbers together to derive a new number and return that number.
Example
Following is the code ?
const arr = [67, 45, '34', '23', 4, 6, '6'];
const mixedSum = (arr = []) => {
let sum = 0;
for(let i = 0; i < arr.length; i++){
const el = arr[i];
sum += +el;
};
return sum;
};
console.log(mixedSum(arr));
Output
185
How It Works
The unary plus operator (+) converts string numbers to integers. When we write +el, JavaScript automatically converts the string '34' to the number 34.
console.log(+'34'); // 34 (number) console.log(typeof +'34'); // "number"
34 number
Alternative Approaches
Using reduce() Method
const arr = [67, 45, '34', '23', 4, 6, '6'];
const mixedSumReduce = (arr = []) => {
return arr.reduce((sum, current) => sum + (+current), 0);
};
console.log(mixedSumReduce(arr));
185
Using Number() Constructor
const arr = [67, 45, '34', '23', 4, 6, '6'];
const mixedSumNumber = (arr = []) => {
let sum = 0;
for(const element of arr){
sum += Number(element);
}
return sum;
};
console.log(mixedSumNumber(arr));
185
Comparison
| Method | Syntax | Performance |
|---|---|---|
| Unary Plus (+) | +element |
Fastest |
| Number() | Number(element) |
Good |
| reduce() | arr.reduce(...) |
Most concise |
Conclusion
The unary plus operator provides the fastest way to convert string numbers to integers for summation. All three approaches handle mixed arrays effectively, with reduce() offering the most functional programming style.
Advertisements
