Develop a chart and compute the total of each individual column

I am interested in creating a class library that can manage user inputs by allowing them to add columns in the UI with a column name and comma-separated values. My goal is to perform calculations with this data and display it in a data table. Specifically, I want to calculate the sum of the entered values for each column, regardless of the number of values entered, and then calculate the total sum of all columns. I am currently facing a challenge in determining how to calculate the sum of each column in the array and then calculate the total sum of those column values. Any assistance would be greatly appreciated.

// class

export class DataTable {
    public constructor(id: string) {
        this.id = id;
    }

    public readonly id: string;
    public rowCount: number = 0;
    public columnCount: number = 0;

    public columnName: string;
    public columnValuesAsCsv: string;
    public listOfColumns: any[] = [];
    public listOfValues: any[] = [];

    public addColumn(columnName: string, columnValuesAsCsv: string) {
           this.columnName = columnName;
           this.columnValuesAsCsv = columnValuesAsCsv;

           this.listOfColumns.push(this.columnName);
           while (this.listOfColumns.push()) {
              this.listOfValues.push(this.columnValuesAsCsv);
              break;
           }
           console.log(this.listOfColumns);
           console.log(this.listOfValues);

           this.rowCount = this.listOfValues.length;
           this.columnCount = this.listOfColumns.length; 
    }
    
    public calculateSum(resSum: number, name: any) {
        if (this.columnName !== null && this.columnValuesAsCsv !== null) {
            for (name of this.listOfColumns) {
                //get the sum of column
                resSum = this.listOfValues.reduce((acc: number, item: string) => acc += parseInt(item), 0);
            }
            return resSum;
        }
    }

// .ts file for UI

import { DataTable } from '../DataTable/DataTable';

export default
    {

        data() {
            return {
                table: new DataTable("ABC"),

                tableId: "",

                columnName: "",

                columnValuesAsCsv: "",

                rowValuesAsCsv: "",

            }
        },
      
        methods:
        {
            onNewTable() {
                console.log(`New Table: ${this.tableId}`);
                // this.table....
            },

            onAddColumn() {
                this.table.addColumn(this.columnName, this.columnValuesAsCsv);
                console.log(this.columnName, this.columnValuesAsCsv);
            },

            onSum() {
                const resSum = this.table.calculateSum();
                console.log(`Sum of column values is: ${name}: ${resSum}`)

            },
        }
    }

https://i.sstatic.net/r5FTC.png

listOfColumns[] contains column names p1, p2 which were user-entered through form fields.
listOfValues[] contains column values for p1 (1,2), p2 (3,4) entered by the user through form fields.
I am aiming to calculate the sum of each column name and display it on the console as follows: "sum of p1 is: 3", "sum of p2 is: 7", and so on.
Lastly, I intend to show: "total sum of columns is: 10" in this case.
I hope this clarifies the situation?

Answer №1

After examining the code, I noticed some parts that may have been intended for other functions, but I have simplified the code to convey the main idea.

  • listOfValues is now an array of numbers that are parsed in the addColumn method instead of a confusing parsing process later on.
  • calculateSum now takes no parameters and returns an object containing an array of [columnName, columnSum] pairs and the total sum (which is calculated using nested reduce functions).
class DataTable {
  public constructor(id: string) {
    this.id = id;
  }

  public readonly id: string;
  public rowCount: number = 0;
  public columnCount: number = 0;

  public columnName: string;
  public columnValuesAsCsv: string;
  public listOfColumns: string[] = [];
  public listOfValues: number[][] = [];

  private arraySum(array: number[]) {
    return array.reduce((acc, item) => acc + item, 0);
  }

  public addColumn(columnName: string, columnValuesAsCsv: string) {
    this.listOfColumns.push(columnName);
    this.listOfValues.push(columnValuesAsCsv.split(",").map(Number));
  }

  public calculateSum() {
    const columnsSum: [string, number][] = this.listOfValues.map(
      (columnValues, index) => [
        this.listOfColumns[index],
        this.arraySum(columnValues)
      ]
    );
    return {
      columnsSum,
      totalSum: this.arraySum(columnsSum.map(([, columnSum]) => columnSum))
    };
  }
}

const dt = new DataTable("id");
dt.addColumn("p1", "1, 2");
dt.addColumn("p2", "3, 4");

const { columnsSum, totalSum } = dt.calculateSum();
columnsSum.forEach(([name, sum]) => console.log(`sum of: ${name} is ${sum}`));
console.log(`total sum of columns is: ${totalSum}`);

https://stackblitz.com/edit/typescript-opp1qz

It might be beneficial to store the data in a Map instead of two separate arrays to make it easier to keep them synchronized when adding, removing, or searching.

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 importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

Tips for updating the class of the body in an Angular 2 and Typescript project

When it comes to managing different classes for the login page versus other pages in an application, there is a need to change the body element's class once the user has logged in. Here is how I am attempting to achieve this: index.html <body [ng ...

In the domain of React and Typescript, a minimum of '3' arguments is anticipated; nonetheless, the JSX factory 'React.createElement' is only equipped with a maximum of '2' arguments. This incongruity is signaled by the

I am facing an error with this particular component: const TheBarTitle = ( theClass: any, columnTitle: string, onClickAction: any, ) => { return ( <div className={theClass} title="Click to add this ...

Creating dynamically generated routes in Angular or Angular 9 before initialization

I'm currently working on a project where I am in the process of converting an AngularJS application to Angular. The main challenge that I am facing at the moment revolves around routing. To sum it up: My requirement is to define routes based on an AP ...

What causes TypeScript to generate an error when using two array of object types, but not when using the shape of both?

There are two basic types of data available: type DataA = { percent: string; exchange: string; }; type DataB = { price: number; exchange: string; }; I'm puzzled as to why TypeScript gives errors when I try to use both types together: const ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

The exported interface's property '<properyName>' is utilizing a private name '<name>'

Here is a new interface declaration: export interface ApiClientMetodOptions { initialFilterSatement?: string; fieldsMapping?: { [K in keyof P]?: string; }; requestParams?: IRequestParams<P>; additionalParams?: { [ ...

Attempting to invoke a promise within a function yields an error message stating that it lacks call signatures

Recently, I came across this interesting class: export class ExponentialBackoffUtils { public static retry(promise: Promise<any>, maxRetries: number, onRetry?: Function) { function waitFor(milliseconds: number) { return new Pr ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Specify the second parameter as a generic class that corresponds to the first parameter of the function

Given the example below, the second parameter of the fn function requires a class with a static attribute controle and an instance attribute controle, both of type number. interface Base { controle: number new(...args: any[]): { controle: n ...

Using Material UI Slider along with Typescript for handling onChange event with either a single number or an

Just diving into Typescript and encountered an issue with a Material UI Slider. I'm trying to update my age state variable, but running into a Typescript error due to the typing of age being number and onChange value being number | number[]. How can I ...

Using TypeScript to pass a callback function to labelFormatter in the legend of a Highcharts chart

I am currently experimenting with integrating HighCharts into an Angular2 project using TypeScript. My goal is to customize the appearance of the legend text, adding an image next to it. I've found that HighCharts provides a labelFormatter property w ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

Theme customization in Material UI includes the addition of a custom color. However, this custom color is missing from the control values in Story

Currently in my project, I am utilizing a stack that includes React 18, TypeScript, MUI 5, and Storybook 6.5. I have been attempting to incorporate custom colors into my MUI Theme and have them reflect in Storybook's dropdown options for the color p ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...

Navigating an immutable list to make updates to its values

Within this list, I have an unalterable group of objects. My task is to change the value of the 'isReq' property to false for all objects except the one with the id 2. [ { 'id': 1, 'name': 'Ram', 'D ...

Creating a Typescript template project: A step-by-step guide

Are there any resources or guides available on creating a Typescript Template project that functions like Dotnet template projects? My goal is to develop a template that can be easily installed on a local machine, pulling the source code from GitHub for a ...

Adjusting table to include hashed passwords for migration

How can I convert a string password into a hash during migration? I've tried using the following code, but it seems the transaction completes after the selection: const users = await queryRunner.query('SELECT * FROM app_user;'); user ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

ERROR TypeError: Unable to access the 'nativeElement' property since it is undefined in Angular 5

I have encountered a problem while working on my application. Although similar issues have been asked before, I believe mine is slightly different. In my application, when a user deletes products from their cart, I want to automatically close the modal wi ...