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

Writing a Javascript function to find the average of digits of a number by recursion

I am trying to find the average the sum of digits of a number.

For example, for the number 123, the sum of digits of 123 is 6 and the number of digits in 123 is 3.
So, the average of digits of 123 is 6/3 = 2.

I’ve only gotten as far as trying to find the sum through recursion unfortunately and often comes up as undefined. If I could figure this out I could find the average comfortably.

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

function averageOfDigits(number) {
//   Make the whole number into a string first to get the individual digits

  let arrOfStr = number.toString().split('');

//   Convert this array into integers
  let arrOfNum = arrOfStr.map(parseFloat)
  
// Find sum of these digits using recursion
  let sum = function sumRecursion (arrOfNum) {
    if (arrOfNum.length === 1) {
      return arrOfNum[0]
    } else {
      return arrOfNum.pop() + sum(arrOfNum)
    }
  } 
}
 

console.log(averageOfDigits(999))

>Solution :

It’s missing the initial call to the recursive function.

Hint:

  return (function sum(arr) {
    if (arr.length === 1) {
      return arr[0]
    } else {
      return arr.pop() + sum(arr)
    }
  }(arrOfNum))
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