Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript For Loop using Arrays to find the Sum of Digits in a String Troubles

I’ve been learning javascript in school for a few months now and I’m trying to work a problem out on my own but I can’t seem to figure out what the issue is. The assignment is to "Create a for loop that starts at zero and loops once for each character in the number using the .length property." So for example, if I were to put in 2514 it should return 12.
Here is the piece I’m struggling with

function sumOfDigits(numberPassed) {

    if (!isNaturalNumber(numberPassed)) {
        return 'bad data';
    } else {
        numberPassed = parseInt(numberPassed)
        let digitSum = 0;
        for (let i = 0; i < numberPassed.length; i++) {
            digitSum = numberPassed[i] + digitSum;

        }
        return digitSum;
    }
}

When I test it in the browser it keeps giving me 0. If anyone could point me in the right direction I would greatly appreciate it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

parseInt() would convert numberPassed into a number. Thus, you wont be able to perform .length method to it.

You’d have to convert it into a string through, numberPassed.toString() and then while you are performing your addition, convert each digit back to INT through parseInt(numberPassed[i]) to get your desired result.

The code would look something like this,

function sumOfDigits(numberPassed) {

    if (!isNaturalNumber(numberPassed)) {
        return 'bad data';
    } else {
        numberPassed = numberPassed.toString()
        let digitSum = 0;
        for (let i = 0; i < numberPassed.length; i++) {
            digitSum = parseInt(numberPassed[i]) + digitSum;

        }
        return digitSum;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading