I am making a calculator where user can past numbers with spaces like 20 30 40 60 50
and it will calculate all in total = 200
How I can convert this string "20 30 40 60 50" to Numbers with spaces? Because I'll than replace the space with +
I am making a calculator where user can past numbers with spaces like 20 30 40 60 50
and it will calculate all in total = 200
How I can convert this string "20 30 40 60 50" to Numbers with spaces? Because I'll than replace the space with +
You can use split
with map
for transform string to number then use reduce
for sum array like:
const string = '20 30 40 60 50';
const arrayNumbers = string.split(' ').map(el => parseInt(el));
const sum = arrayNumbers.reduce((sumCounter, a) => sumCounter + a, 0);
console.log(arrayNumbers, sum);
Please note: If you plan to use decimals use parseFloat
instead of parseInt
Reference: