I think I’m close to solving this one The goal here is the find the Numbers in the string and add them together to find the sum of them.
there are numbers and letters in the strings in question
instruction:
- PART 2
- Create a getStringSum(str) function that returns the sum of any integers that are in the string.
- Example1: getStringSum("GH2U87A") => 17
- Example2: getStringSum("GHIUJUHSG") => 0
- */
Where I’m at:
function getStringSum(str) {
let sum = 0;
for(let i = 0; i < str.length; i++){
if (str[] == typeof Number){
sum += str[i];
};
};
return sum;
};
I have my for loop condition set to iterate through the string, but I don’t think my "typeof" proterty is registering the Numbers in the string as numbers, because theyre are within a string, I’m not certain thats the case, but I’m guessing thats whats happening, so my biggest question, is how to re assign the numbers, or identify the numbers in my string, to the value of number . any help or advice / push in the right direction is greatly apprecitated, thank you!!
2
Answers
It’s not clear to me what you think
str[] == typeof Number
means.If you want to sum all integers in a string, you’ll need to try to convert each character to a number, and only add them to the sum if they’re not NaN. This is because
Number
will returnNaN
if it fails.Either as a for loop:
Or using the built-in functions:
Step 1: Split the string into an array
Step 2: Declare a variable to store your answer.
Step 3: Iterate through the array using forEach and try converting each element into an integer. If the conversion is successful add the element to the answer variable.
Step 4: Console.log your answer to see the answer.
Now, create a function to do this all for you: