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?