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

122
Visualizações
Typescript reduce I want to sum numbers but the previous value becomes string

I have a typescript function which traverse an array of objects, and summary them. It was working if I implicit gives the value a number, however if it comes from input it converts the value to string.

const mmrChanges = matches.reduce<IHistory[]>(
     (previous: IHistory[], match: IMatch, index: number) => {
       const mmrChange = (match.party_size > 1 ? 20 : 30) * isWon(match); // party game 20 mmr, solo game 30
       const prevMmr = previous[previous.length - 1].value;
       return [
         ...previous,
         {
           index: index,
           value: prevMmr + mmrChange,
           time: new Date(match.start_time * 1000).toISOString().split("T")[0],
         },
       ];
     },
     [{ index: 0, value: currentMmr, time: "" }]
   );
   console.log(mmrChanges);

value type is : (property) IHistory.value: number and the current mmr is: const currentMmr: number

However when I start to accumulate the value numbers it starts to concatenate values as strings. currentValue = 400

the next iterate it becomes:

{
    "index": 0,
    "value": "40030",
    "time": "2022-01-25"
}

I tried to force it to number explicitly inside the reduce function with "as number" Also I tried the parseInt() function, but then typescript throws error I cant transform number to int.

What am I missing here? If I change the currentMmr to 0 it is working as intended.

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

0

This solution below seem to have achieved the desired results:

const mmrChanges = matches.reduce<IHistory[]>(
     (previous: IHistory[], match: IMatch, index: number) => {
       const mmrChange = (match.party_size > 1 ? 20 : 30) * isWon(match); // party game 20 mmr, solo game 30
       const prevMmr = previous[previous.length - 1].value;
       return [
         ...previous,
         {
           index: index,
           value: prevMmr + mmrChange,
           time: new Date(match.start_time * 1000).toISOString().split("T")[0],
         },
       ];
     },
     [{ index: 0, value: parseInt(currentMmr.toString()) || 0, time: "" }]
   );
console.log(mmrChanges);

What changed?

The .reduce aggregator was set to [{ index: 0, value: parseInt(currentMmr.toString()) || 0, time: "" }]

Why?

In the question, currentMmr could be any value. In order to ensure that it is always an int, the value prop is set as parseInt(currentMmr.toString()). The .toString() ensures that in case currentMmr is an integer, it is still treated as a string. And, the parseInt transforms the string into an int.

Note: This solution caters to this particular question. It may not work AS IS in other contexts and may need to be customized.

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