How can I calculate the sum using TypeScript while grouping by with the reduce function in JavaScript?

I've successfully implemented grouping by using the reduce function in typescript with my javascript. However, I'm struggling to figure out how to sum another property.

Currently, everything is grouped by the property: pacct (which is working).

The issue arises when trying to sum the property: quantity.

If anyone could provide assistance, it would be greatly appreciated.

Below is the export interface from another .ts file:

export interface TradeData {
  id: number;
  filedate: Date;
  poffic: string;
  pacct: string;
  quantity: number;
  sector: string;
  psdsC1: string;
  name: string;
  bbsymbol: string;
  last_price: number;
  deltasettlement: number;
}

Here is the code snippet where I use reduce:

const result = trades.reduce((groupedAccounts, trade) => {
  const account = trade.pacct;
  if (groupedAccounts[account] == null) groupedAccounts[account] = [];
  groupedAccounts[account].push(trade);
  return groupedAccounts;
}, {} as Record<string, TradeData[]>);

Answer №1

For the calculation, we will initialize reduce with a starting value of 0, and then add the quantity for each trade to the total.

const sum = trades.reduce((total, trade) => total + trade.quantity, 0);

The function returns the updated value for total, which can be visualized as follows:

const callback = (total, trade) => total + trade.quantity;

const initialValue = 0;

let total = initialValue;

for (const trade of trades) {
    total = callback(total, trade);
}

To calculate the sum for each group, we iterate through each group using Object.entries:

const entries = Object.entries(groups);

We then update each entry by calculating the total sum of quantities in the group:

const summed = entries.map(([key, group]) => {
    const sum = group.reduce((total, trade) => total + trade.quantity, 0);

    return [key, sum];
});

Finally, we convert the entries back into an object using Object.fromEntries:

const transformed = Object.fromEntries(summed);

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

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

AngularJS full height style with Google Maps integration

I'm having trouble displaying a full-height Google map on my website. <section data-ng-controller="LocationsController" data-ng-init="find()"> <map center="41.454161, 13.18461" zoom="6"> <span data-ng-repeat="location in locations" ...

What are some ways to implement dangerouslySetInnerHTML in conjunction with read-more-react from npm?

Is there a way to include dangerouslySetInnerHTML in a text field without receiving an error? <ReadMoreReact text={yourTextHere} min={minimumLength} ideal={idealLength} max={maxLength} readMoreText={read ...

Error: Unable to access the 'offsetTop' property of null

I attempted to implement a scroll effect in my project. The goal was for users to be taken to a specific section when they clicked on an option in the navbar. However, I encountered an error during implementation. Below is the code snippet where the error ...

How can I prevent my mouse click from being overridden by my mouse hover?

Currently, I am developing a Sudoku game using JavaScript and facing some challenges with mouse events. My goal is to enable users to hover over a square and have it change color, as well as click on a square to highlight the entire row, column, and quadra ...

What are the steps to programmatically click a JavaScript button with Selenium and Python?

Imagine there is a button on a webpage that looks like this: <input type="submit" name="next_btn" value="Next" onclick="gonext();" id="btnNext"> When manually clicked, it takes approximately 3-6 seconds for the page to reload and show new content. ...

Differences between Mongoose's updateOne and save functions

When it comes to updating document records in a MongoDB database, there are several approaches to consider. One method involves defining the User model and then locating the specific user before making modifications and saving using the save() method: let ...

What is the best way to incorporate rows from JSON data into my table?

I have a backend function that returns a JSON file containing values. I need to extract specific information from this JSON data and populate input fields within a table dynamically, based on the amount of data retrieved. Example JSON Data [ { "Type ...

Contrast various values with a single variable

I am in need of a more efficient way to compare a long list of strings against the same variable. Is there a more concise approach I could take? if(val=="kivi" || val=="apples" || val=="lychee" || val=="banana.C" || val=="mangos") ...

The outerHeight of Elements measured in pixels

Is there a way to increase the outerHeight() function by adding extra pixels? Let's say we have a variable storing the outerHeight of .pg-sect: var $section = $('.pg-sect').outerHeight(); Now, if I want to add an additional 70px to the he ...

Does NextJS come with an index.html template page pre-installed?

Today, I delved into NextJS for the first time as I transitioned a ReactJS website over to it. While I find it to be a powerful framework, there is one particular feature that seems to be missing. In traditional ReactJS (without the NextJS framework), we ...

What could be causing compatibility issues between jQuery and Bootstrap 4 alpha 6?

I am encountering issues while trying to utilize jQuery in my project. Despite rearranging the script tags, I haven't been able to resolve the errors. Below is a snippet of the code: <!DOCTYPE html> <html lang="en"> <head> < ...

Tips for organizing a JSON object's keys into separate arrays while eliminating any duplicates

Take the JSON data provided and group it by keys, creating an array of unique values for each key (excluding duplicates). var people = [ {sex:"Male", name:"Jeff"}, {sex:"Female", name:"Megan"}, {sex:"Male", name:"Taylor"}, {sex:"Female", na ...

How to delete a div element in Material UI's Date Picker

In my project, I am utilizing Material UI's simple Date Picker module. However, I am looking to solely display the calendar section without the month and year indicators along with the navigation arrows. Is it possible to remove these specific element ...

Validation of forms in AngularJS/HTML5 that are nested within one another

Just starting out with AngularJS and experiencing issues with HTML5 nested form validation. I currently have 2 forms; mainFrm (parent form) and stateFrm (a child form). I am struggling to validate each form within its own scope. <form id="mainFrm" ng- ...

Updating the web browser does not display the changes made on the page

Currently diving into the world of Angular and I've successfully cloned the repository. After installing the dependencies using npm, I have the web server up and running smoothly. Accessing the page on localhost:4000 works like a charm. Interestingly ...

PHP variable missing "+" sign at the end after post operation

I have encountered a unique problem that I cannot seem to find anywhere else. My issue lies in adding grades ending with a plus sign, such as B+, C+ or D+. I am able to add grades like A-, B-, C- and D- without any problem, but when it comes to adding a g ...

Can C language run JavaScript code?

Suppose I have a piece of JavaScript code, and I want to create a basic console program that will read the code, run it, and display the output. Is this achievable? If so, where should I begin? Thank you. ...

Unexpected issue with AngularJS Select2 multiple feature: ng-selected not functioning as expected

I have been working with the code below to select an item if it is present in the filters: <div ng-repeat="category in categories.data" ng-model="div1"> <div ng-repeat="(key, value) in category" mg-model="div1.div2"> ...

Tips for setting `Cache: false` with the $.getJSON() function

I'm experiencing a caching problem with ajax calls in IE 10. The solution I found is to include cache: false in the ajax call, but I'm still having issues. How can I properly include Cache: false in my code? $.getJSON(url , function(data){ //som ...