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

233
Visualizações
Use reduce to sum all values of an array passed via a console log

I'm trying to get the total of an array passed via a console log. However instead of adding the numbers it's returning the array with a 0 in front.

This is what I have tried

const sum2 = (array) => {
  let total = 0;
  const totalFigure = array.reduce((total, number) => {}, 0)
  return total + array
}

console.log(sum2([1, 3, 5, 7, 9]));

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Since you are not doing anything to reduce your array in that function

(total, number) => {}

and your initial value is 0, you are just adding 0 to your array by returning

total + array

You are never summing up your array. total + array turns into 0 + array.toString() which creates the 01,3,5,7,9 you are seeing.

If you want to sum up the values of you array, this is one approach:

const sum2 = (array) => array.reduce((total, number) => total+=number, 0)

console.log(sum2([1, 3, 5, 7, 9]));

(total, number) => total+=number

this increments the initial value (which total is first set to) by number, adding them together and returning them to the next iteration of the reduce function

about 4 years ago · Juan Pablo Isaza Relatório

0

Array.prototype.reduce() accepts callback function where the first parameter of the callback is "total" value calculated in previous iteration of loop and current value of iteration as the second parameter. The final code could look like this:

const sum2 = arr => {
  const result = arr.reduce((total, number) => {
    return total + number;
  }, 0);

  return result;
};

And shorter:

const sum2 = arr => arr.reduce((total, number) => total + number, 0);
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