

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to force JavaScript to do math instead of putting two strings together?
Let’s say, we have an array of strings, basically it is an array of number strings like this −
const arr = ['3', '3', '55', '23', '67', '43', '12', '67', '87', '12'];
We are required to write a JavaScript function that takes in one such array and returns the sum of all elements of this array instead of concatenating the string to one another.
Let’s write the code for this function −
Example
const arr = ['3', '3', '55', '23', '67', '43', '12', '67', '87', '12']; const sumString = arr => { const num = arr.reduce((acc, val) => { const sum = acc + (+val || 0); return sum; }, 0); return num; }; console.log(sumString(arr));
The unary (+) operator, before any string forces explicit type coercion from type String to type Number, if the first character of the string is not a valid number, then NaN is returned otherwise a valid number is returned.
Output
The output in the console will be −
372
- Related Questions & Answers
- How to force MongoDB to use the BasicCursor instead of an index?
- Adding binary strings together JavaScript
- How to force MySQL to connect by TCP instead of a Unix socket?
- Can we do math operation on Python Strings?
- How to do Python math at command line?
- How To Do Math With Lists in python ?
- How to merge two strings alternatively in JavaScript
- How to plot two histograms together in R?
- How to do case insensitive string comparison of strings in JavaScript
- How do you force MySQL LIKE to be case sensitive?
- How to visualize two categorical variables together in R?
- How do you feel about putting pineapple on pizza?
- Twice join of two strings in JavaScript
- Finding gcd of two strings in JavaScript
- How can I force clients to refresh JavaScript files?
Advertisements