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

221
Visualizações
Sum negative and positive numbers in array to get a result

i'm stucked with a simple logic, i have an array as a result that contains positive and negative numbers.

what i need is to sum both negative and positive and print a result

const arr = ['-8', '-3', '1', '-4', '0']
// expected results = -14

what i've tried so far is to separate negative and positive with:

 const positive = scores.filter(posNumber => posNumber >= 0)
 const negative = scores.filter(negNumber => negNumber < 0)

but if i perform a reduce on positive i get "010" as a result....

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Those are strings. You need to convert them to Numbers first:

const arr = ['-8', '-3', '1', '-4', '0'].map(Number);
const positive = arr.filter(posNumber => posNumber >= 0);
const negative = arr.filter(negNumber => negNumber < 0);
const positiveSum = positive.reduce((sumSoFar, current) => sumSoFar + current, 0);
const negativeSum = negative.reduce((sumSoFar, current) => sumSoFar + current, 0);

Or just

const arr = ['-8', '-3', '1', '-4', '0'].map(Number);
const sum = arr.reduce((sumSoFar, current) => sumSoFar + current, 0);

for the overall sum.

about 4 years ago · Santiago Trujillo Relatório

0

The problem here is that your array is actually an array of strings instead of numbers. So in reality, you need to convert the array to an array of numbers and then you can sum the values.

const arr = ['-8', '-3', '1', '-4', '0'];
const sum = arr.reduce((acc, value) => acc + Number(value), 0); // -14
about 4 years ago · Santiago Trujillo Relatório

0

   let sum = 0
    arr.forEach(s => sum+= +s) 
     console.log(sum)

"+s" convert the value to an integer. You can use parseInt

about 4 years ago · Santiago Trujillo 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