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