Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report

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 Report

0

Perhaps not use the += shorthand?

prev["Exec Qty"] = Number(prev["Exec Qty"]) + Number(qty);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!