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
Here's how you would use reduce to calculate the sum -
[...String(123)].map(Number).reduce((a,b) => a+b, 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
});