Reputation: 1227
I have data in which there are arrays. in the array, there is a value which is claimed_value. I need the sum of all claimed_value of arrays. an example I have array all have the claimed_value. but I need to sum of all the claimed_value which have the status=settled in the array.
this is how I'm calling the API.
getClaims(){
if(this.userFilter.company_id){
let url =
'http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-
api/get_claims.php?company_id='+this.userFilter.company_id;
}else{
let url =
'http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-
api/get_claims.php?offset=0&limit=200';
}
this.clientData = this.httpClient.get(url).
subscribe(data => {
console.log(data);
this.data = data.records;
var status = 'settled';
var status2 = 'submitted';
var countsettled = this.data.filter((obj) => obj.status ===
status).length;
var countunsettled = this.data.filter((obj) => obj.status ===
status2).length;
console.log(countsettled);
this.countsettled = countsettled;
console.log(countunsettled);
this.countunsettled = countunsettled;
});
}
Upvotes: 1
Views: 1651
Reputation: 36
let finalSum = 0;
this.data.forEach((item) => {
if(item.status === 'settled'){
finalSum += item.claimed_value
}
});
console.log("final sum is ", finalSum);
Hello, This will loop on all the arrays in your data list , and add the number of claimed_value
to the finalSum
.
Hope this will work for you.
Upvotes: 0
Reputation: 1843
Your question is more general javascript
than angular
You can sum element of array by using the Array.reduce
function
You can sum on a specific status by filtering first
Ie
const sum = this.data.filter(item => item.status === 'settled')
.reduce((acc, item) => acc + Number(item.claimed_value), 0);
Note that as said in comment you received a string
and not a number
so you must convert it at first (see the Number() function in the
reduceclosure)) otherwise the
+` operator will just concatenate the string
Upvotes: 4