Sunilkumar Mandati
Sunilkumar Mandati

Reputation: 189

How to sum a column based on the passed column name dynamically

I have the following sample data.

ELEMENT_DATA: PeriodicElement[] = [
  { position: '06703851', weight: 10, billamount: 200, },
  { position: '06703852', weight: 20, billamount: 300, },
  { position: '06703853', weight: 30, billamount: 400, },
  { position: '06703854', weight: 40, billamount: 500, }
];

I get a column name dynamically and I need to perform the sum of that column. For instance, if the weight column is passed, I should sum the weight column and return the sum. I tried the following code and it's giving an error at t => selectedColumn. Please help!!

caltotal(selectedColumn: string) {
  this.total = this.ELEMENT_DATA.map(t => selectedColumn).reduce((acc, value) => acc + value, 0);
}

Upvotes: 0

Views: 100

Answers (1)

Yong Shun
Yong Shun

Reputation: 51485

  1. Your class/interface has to modify to support with index signature.
class PeriodicElement {
  position!: string;
  weight!: Number;
  billamount!: Number;
  [key: string]: any;
}
  1. Access the property value with the index signature.

    2.1. For the scenario with property is not a Number type, you may check its type first and for my use case I default the value as 0 for property which is not a Number type.

caltotal(selectedColumn: string) {
  this.total = this.ELEMENT_DATA.map(t => t[selectedColumn])
    .reduce((acc, value) => acc + (typeof value === 'number' ? value : 0), 0);
}

Demo @ TypeScript Playground

Upvotes: 1

Related Questions