简体   繁体   中英

Angular need to sum the values of array

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;

  });

 }

在此处输入图像描述

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 reduce closure)) otherwise the +` operator will just concatenate the string

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM