Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda