skip to Main Content

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


  1. 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 return NaN if it fails.

    Either as a for loop:

    let sum = 0;
    for (const c of str) {
        const num = Number(c);
        if (isNaN(num) continue;
    
        sum += num;
    }
    

    Or using the built-in functions:

    str.split("").map(Number).filter( (v) => !isNaN(v)).reduce( (acc, v) => acc + v, 0)
    
    Login or Signup to reply.
  2. 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"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search