Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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);