An issue arises when trying to group and sum an array of objects due to difficulty converting strings to arrays in TypeScript

Below is the provided code snippet:

Definition of Interface -

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

Data Collection -

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",
        },
      ];

Aggregation and Grouping Process -

      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 final Output -

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

Query on Converting String to Number.

Desired Outcome -

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

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

Answer №1

Consider updating your code with the following snippet, which will provide the correct string output.

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

Answer №2

To convert the value of prev["Exec Qty"] to a number, simply apply the following transformation:

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

Answer №3

Maybe consider avoiding the use of the += shortcut?

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Collaborate by sharing local storage with other systems

One of my systems (x.x.x.x: 8000) creates a localstorage after logging in. Now, when a user interacts with another system (x.x.x.x: 8001) by clicking a specific button, the information stored in the initial system's localstorage (x.x.x.x: 8000) is nee ...

Experiencing difficulties while trying to showcase a PDF within the Expo Go app

I am currently developing a React Native application that requires the display of PDF files. I have tried two different methods, one using react-native-webview and the other with react-native-pdf, but both approaches are presenting challenges. This is how ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Using Jquery and CSS to add a class with a 1-second delay when the mouse enters

I have successfully implemented the addClass function in my code, but I'm encountering issues when attempting to use delay or setTimeout functions. It's important to note that I'm avoiding the use of webkit attributes in CSS. If anyone has ...

Retrieve information from a JSON API on one server and showcase it on an HTML page hosted on a different server

I have a situation where I need to transfer data from one project (Project1) to another project (Project2). To achieve this, I decided to convert the Project1 data stored in a database into a JSON API and then call it using an HTML page from Project2. Howe ...

Encountering issues while attempting to pass a function into axios.then and catch and receiving errors

axios.post('http://localhost:3000/api/v1/login', { email: this.state.email, password: this.state.password }, { headers: { "Access-Control-Allow-Origin": "*", ...

Any suggestions on how to incorporate the variable into the inline JavaScript [[]] API path?

I have a query regarding creating a URL in JavaScript, but I'm unsure how to include variables within th:inline="javascript". Below is my code snippet: <script th:inline="javascript"> $(function() { $('#querySubmit').click(queryS ...

The issue with getting a token from Next-auth on the server side persists

Currently, I am working on an application using Next.js and implementing authentication with NextAuth. However, I am encountering an issue with the getToken function not working properly on the server-side. I have double-checked my callbacks configuration ...

Angular Error: secure is not defined

Encountering the 'safe is undefined' error while interacting with HTML that has been dynamically inserted into a page via an AJAX call. For example, when selecting an option from a dropdown within this HTML, the error occurs and the dropdown rese ...

How can I get rid of the table borders and set colors for every other row in the

How can I remove the border lines from a table and assign colors to alternate rows in the table? Follow this link for the code: https://stackblitz.com/angular/kooxxyvddeqb?file=app%2Ftable-sticky-columns-example.css Thank you in advance ...

Grunt: Can you explain the concept of recursive templates?

Hey there, I'm new to using Grunt and I've run into a puzzling issue with recursive templates. Let me provide you with a concrete and straightforward example: var path = require('path'); module.exports = function(grunt) { grunt.init ...

"Enhance Your Website with Multiple Video Streams using YouTube API Events

Hello everyone! I am looking to include multiple videos on my website and have them start playing automatically when a user scrolls and the videos are in view. I want the speakers to be muted by default using the mute() function. Previously, I had succes ...

There seems to be an issue with the syntax in ReactJS: the URL is

I'm facing an issue in my React code. I have a function that doesn't seem to be in the correct format for React. check(img) { console.log(img,typeof img) const url=""; const arrN = ["15","16","35","36","37","38","39","40" ...

What happens if I attempt to access an undefined value from a JSON array?

I've been attempting to nest a JSON array within another JSON array. I believe I have structured it correctly, but when I try to access the second array, it returns undefined. JSON example : var data = [ {"Items" : [ {"item1" : "item1 ...

Transferring information among various instances of a single controller (ng-controller)

I am relatively new to using Angular and I am facing a challenge with a seemingly simple task that is proving to be more complex within the framework. The issue at hand involves data manipulation, specifically with a variable named var1. I am modifying th ...

The hamburger menu on the navigation bar only functions the first time it is clicked

I've encountered an issue with my hidden menu nav bar. The hamburger and close buttons only work once. Should I organize the events within a function and call it at the end, or perhaps use a loop for the button events? It's worth noting that I d ...

Attempting to flip the flow of marquee loop in javascript

I am currently modifying this code to create a left-to-right marquee instead of the original right-to-left one. However, after successfully changing the direction, the text no longer loops as it did originally. I'm stuck and can't seem to figure ...

Top method for troubleshooting JavaScript code in Visual Studio 2010

Is there a way to troubleshoot JavaScript code in Visual Studio 2010 for MVC Razor projects? ...

PhoneGap and jQuery prove ineffective in fetching json results from Twitter

I've been working on a project to fetch the most recent 50 tweets with a specific hash tag. The project is built for mobile devices using PhoneGap (0.9.6) and jQuery (1.6.1). Below is my code: function retrieveTweets(hash, numOfResults) { var uri ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...