Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Zolbayar Orshil
Zolbayar Orshil
9,838 Points

Add all the numbers in string like "123456" to loop through like 1+2+3+4+5+6 and return the sum

I need to add all the number of some random number like var myNum = ["1233445", "1213332"]; compare the sum of these to like i mean 1+2+3+3..... and the another one 1+2+1+3+3+3.... thanks

3 Answers

Erik Nuber
Erik Nuber
20,629 Points

You can do this...

var number = 12354987,
    output = [],
    sNumber = number.toString();

for (var i = 0; i < sNumber.length; i++) {
    output.push(sNumber.charAt(i));
}

console.log(output);

This will give you an array like

["1", "2", "3", "5", "4", "9", "8", "7"]

You can then iterate through the array and use the parseInt() method to get each individual number and add them together.

var addedSum 

for (var i=0; i < output.length; i++) {
   addedSum += parseInt(output[i])
}

You could make the above functions as well so you can call it on multiple numbers. However you would need to store each of those numbers into different variables in order to compare the sums of them.

Thomas Nilsen
Thomas Nilsen
14,957 Points

something like this:

function sum(arr) {
    var sum = 0;
    for (var i = 0; i < arr.length; i++) {
        sum += arr[i].split('').map(str => parseInt(str)).reduce((a,b) => a+b);
    }
    return sum;
}


var sum = sum(['1233445', '1213332']);

console.log(sum);