Search code examples
javascriptloopsfor-looptypeof

Finding the sum of Numbers in a string containing letters and numbers using javascript & for loops


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!!


Solution

  • Step 1: Split the string into an array

    let str = "GHIUJUHSG"
    let newStr = str.split('');
    

    Step 2: Declare a variable to store your answer.

    let answer = 0;
    

    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.

       newStr.forEach(item => {
            if(parseInt(item)){
                answer = answer + parseInt(item)
            }
        })
    

    Step 4: Console.log your answer to see the answer.

    console.log("answer: ", answer)
    

    Now, create a function to do this all for you:

    let str = "GHIUJUHSG"
    const findNumberAndSum = (str) => {
        let answer = 0;
        str.split('').forEach(item =>{
            if(parseInt(item)){
                answer = answer + parseInt(item);
            }
        })
        return answer;
    }
    console.log(findNumberAndSum(str)) //The result should be 0 in case of "GHIUJUHSG" and 17 in case of "GH2U87A"