Confused on this one and not sure if I need to use parseInt or what. But I have an array right now and am iterating through, but I need to add them together?
Instructions:
Write a function named sumLetters that returns the sum of every character in the string
Example:
If you pass "45" it should return 9
If you pass "246" it should return 12
My code:
function sumLetters(str) {
let sum = 0;
let splitStr = str.split('');
for (let i = 0; i < splitStr.length; i++) {
}
return sum;
};
No, just a horrible function name haha
That means all the test cases have numbers as arguments right?
Is there a more logical way to go about this?
function sumLetters(str) {
let sum = 0;
let splitStr = str.split('');
for (let i = 0; i < splitStr.length; i++) {
sum += parseInt(splitStr[i])
}
return sum;
};
Seems to work?
EDIT: Now, I’m trying not to split the string and just work from there…I have this currently:
function sumLetters(str) {
let sum = 0;
for (let i = 0; i < str.length; i++) {
sum += str[i];
}
return sum;
};
Hard to keep up with that second one. I’m hardly familiar with for…of loops?
If you think about strings as an array of characters, then the for… (of) loop simply iterates over every character in that string.
In the second example, again treating str as an array of characters, use the spread operator to actually make it an array, then use the Array.reduce() function to sum each character. It is a fairly advanced way of looking at functions, using the “fat arrow function” and its shorthand, but when you get comfortable with that approach, it make sense. Rather than seeing how you should iterate over a collection of things (“should I use a for loop?”, “should I use a while loop?”), you simply see what you want to do with the data itself.
Methods like reduce, map, and filter are great in that they abstract the how and leave you to handle the what.