0

I just started learning about reduce method, and stuck in this problem...

  N   answer
123   6
987   24

An example would be 9 + 8 + 7 = 24 but the parameter is in number.

Here is what I have tried:

function solution (n){
   let result = new Array (n)
   let answer = result.reduce((a,b) => {
       return a + b 
   })
}

Here is my code but I'm getting TypeError [Error]: Reduce of empty array with no initial value

DBS
  • 9,110
  • 4
  • 35
  • 53
EIK
  • 11
  • 3
  • you instantiated an empty array of size n. It doesn't contains anything. You input is a string so convert it to a array of char n.split('') or [...n] or Array.from(n) then you can do map to int and use your reduce operation – JEY Nov 15 '21 at 17:20
  • Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Randy Casburn Nov 15 '21 at 17:20
  • this-> `(''+123).split('').reduce((acc,n)=>acc+=parseInt(n),0);` – Randy Casburn Nov 15 '21 at 17:25

2 Answers2

1

Here's how you would use reduce to calculate the sum -

[...String(123)].map(Number).reduce((a,b) => a+b, 0)
chunkydonuts21
  • 79
  • 1
  • 10
0

This:

let result = new Array (n)

creates an empty array with a length of n.

In order to convert a number to an array of digits, you can use this little handy snippet:

const arr = n.toString().split('').map(Number)

We are getting n as a string, then splitting it into an array of characters, and then mapping each character to its corresponding digit.

After that you can use the reduce function:

let answer = arr.reduce((a,b) => {
    return a + b 
});
Michael Haddad
  • 4,085
  • 7
  • 42
  • 82