Home > OS >  typescript - group and sum array of objects - problem with casting string to array
typescript - group and sum array of objects - problem with casting string to array

Time:12-20

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' } ]

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

CodePudding user response:

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));
            }

CodePudding user response:

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

prev["Exec Qty"] = String(Number(prev["Exec Qty"]!)   Number(qty));

CodePudding user response:

Perhaps not use the = shorthand?

prev["Exec Qty"] = Number(prev["Exec Qty"])   Number(qty);
  • Related