Is there a way to calculate the sum of values based on the name without repetition in "dataGrf"? I've tried various methods but am facing difficulties. Here is a brief example below to help illustrate what I'm attempting to achieve.
Note: Please excuse any errors in my English
Example) data: = [
{ 'id': 1, 'value': 10, 'name': 'Mary' },
{ 'id': 2, 'value': 5, 'name': 'John' },
{ 'id': 3, 'value': 2, 'name': 'Mary' },
{ 'id': 4, 'value': 3, 'name': 'Lauren' },
{ 'id': 5, 'value': 2, 'name': 'Lauren' },
{ 'id': 6, 'value': 6, 'name': 'Mary' },
];
expected result:
dataGrf: [
{ 'name': 'Mary', 'valueAcum': 18 },
{ 'name': 'John', 'valueAcum': 5 },
{ 'name': 'Lauren', 'valueAcum': 5 }
]
My ChartModel:
export class ChartModel {
constructor(
public name?: string,
public valueAcum?: number
) { }
}
Function used for calculation:
loadData() {
this.loading = true;
this.dataChart.emit(null);
this.dataService.getData(this.year, this.month).
subscribe((data: dataModel[]) => {
let dataSort: dataModel[];
dataSort = data.filter(f => f.value> 0)
dataSort = dataSort.sort((a, b) => a.value> b.value? -1 : 1)
this.dataChart.emit(dataSort);
this.dataGrf = new Array<ChartModel>();
let valueAcum= dataSort.reduce((sum, record) => {
let nameArea = data.map(f => f.name);
nameArea = nameArea.filter(function (item, pos) {
return nameArea.indexOf(item) == pos;
});
if (record.name === nameArea[0]) {
return sum + record.value;
}
return sum;
}, 0);
dataSort.forEach(f => {
this.dataGrf.push(new ChartModel(f.name, valueAcum))
});
this.loading = false;
}
}