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

166
Vistas
typescript - group and sum array of objects - problem with casting string to array

Here is the code -

Interface -

interface IWEXInterface {
  readonly Date?: string;
  "Exec Qty"?: string;
  readonly Expiry?: string;
}

Data -

let data: IWEXInterface[] = [
        {
          Date: "8/30/2021",
          "Exec Qty": "13",
          Expiry: "17/09/2021",
        },
        {
          Date: "8/30/2021",
          "Exec Qty": "15",
          Expiry: "17/09/2021",
        },
        {
          Date: "8/30/2021",
          "Exec Qty": "13",
          Expiry: "17/09/2021",
        },
      ];

Sum and group the objects -

      const sums = [
        ...data
          .reduce((map, item) => {
            const { Date: key, "Exec Qty": qty } = item;
            const prev: IWEXInterface = map.get(key);

            if (prev) {
              prev["Exec Qty"]! += Number(qty);
            } else {
              map.set(key, Object.assign({}, item));
            }

            return map;
          }, new Map())
          .values(),
      ];

      console.log(sums);

The output -

[ { Date: '8/30/2021', 'Exec Qty': '131513', Expiry: '17/09/2021' } ]

How can I cast the string to number.

Wanted output -

 [ { Date: '8/30/2021', 'Exec Qty': 41, Expiry: '17/09/2021' } ]

.............................................................................................................

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

try to replace your code with this one, it will return a string but the right one.

     if (prev) {         
    prev["Exec Qty"]! = (Number(prev["Exec Qty"])+ Number(qty)).toString()
            } else {
              map.set(key, Object.assign({}, item));
            }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Just cast prev["Exec Qty"] to number:

prev["Exec Qty"] = String(Number(prev["Exec Qty"]!) + Number(qty));
about 4 years ago · Juan Pablo Isaza Denunciar

0

Perhaps not use the += shorthand?

prev["Exec Qty"] = Number(prev["Exec Qty"]) + Number(qty);
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