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

166
Visualizações
The reduce fuction sum isn't reducing the elements in an array to a single element?

let newton = ["1", " 2", " 3", " 4", " 5"];

let newton2 = newton.reduce(sum);

function sum(total, value) {
  return (total + value);
}
document.getElementById("demo").innerHTML = newton2;
<p id="demo"></p>

So...I have used the reduce function (sum) and its not summing the elemenets in the array and displaying it in a single element, Rather its displaying the elements in the array again.

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

0

It's working correctly if you use number instead of strings; let newton = [1,2,3,4,5];

Alternatively you can parse string to integer if that's what you want return(total + parseInt(value)); but then you have to initialize aggregator as integer giving it an initial value, otherwise it'll still be casted to string; newton.reduce(sum, 0).

about 4 years ago · Juan Pablo Isaza Relatório

0

You should Cast string to int and then use reduce function.

 function sum(total,value){
     var intVal = parseInt(value);
      return(total + intVal);
    }
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