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

a split-function that accept a string and splits it into value , then sum them up

//Write a function ‘SplitFunction’ that accepts the string ‘7+12+100’ and splits it into individual values, then summing these values. (Make use of the split() and parseInt() functions). Return the summed result.
you can see the question above, and my code for this question is:

function SplitFunction(str){
let y=str.split('+')
let sum=0
for(i=0;i<y.length;i++){
  sum+=parseInt(y[i])
  return sum  
}
}
console.log(SplitFunction('7+12+100'))

But I keep getting results as 7??? and cant find out why

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 :

Just move return sum beyond for loop

function SplitFunction(str){
let y=str.split('+')
let sum=0
for(i=0;i<y.length;i++){
  sum+=parseInt(y[i]) 
}
return sum
}
console.log(SplitFunction('7+12+100'))

Edit

or you can use this clear code below:

var SplitFunction = str => { // taking function called SplitFunction which takes an arguement str
    let sum = 0 // set a variable to sum up
    str.split(+).forEach(number => { // split taken problem and for each of them:
        sum += parseInt(number) // cast to Number and add to sum
    })
    return sum // finally return result
}
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