Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
Using Reduce method

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

[...String(123)].map(Number).reduce((a,b) => a+b, 0)
about 4 years ago · Juan Pablo Isaza Report

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 
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!