Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda