Search code examples
javascriptarraysrecursionsumaverage

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.

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