I am looking to display the sum the amount values in my json objects after I apply a pipe filter that filters them by the objects' name value. So far I can filter the numbers by the name values of their .json objects, but I cant find and display the sum with a .reduce() method in a pipe.
How can I display the sum of amount totals that have been filtered by name values by my pipe?
Eventually I'd like users to search for a city and see a sum total of each object's numeric value that is identifiable by the same city name.
(I'm building off this tutorial https://www.youtube.com/watch?v=sVTNaYBVP88&list=PL4cUxeGkcC9jqhk5RvBiEwHMKSUXPyng0&index=22)
json sample
[
{
"name": "Bacon",
"belt": "purple",
"amount": 23
},
{
"name": "Alex",
"belt": "purple",
"amount": 24
},
{
"name": "Alex",
"belt": "black",
"amount": 232
}
]
Component HTML
<li *ngFor="let ninja of ninjas | filter:term | sum" >
<p>{{ninja.amount}}</p>
</li>
sum pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sum'
})
export class SumPipe implements PipeTransform {
transform(ninjas: any, term: any): any {
return ninjas.reduce(function(a,b){return a + b});
}
}
I don't think you can. Filter the data in xour component or a service and assign the filtered redult to a field an bind
ngFor
to that field. Calculate the sum from that filtered data and assign it to a field and bind the view to that fielf.