Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda