Pravu
Pravu

Reputation: 608

Get SUM of value in Array

I want to get sum of the values in array. With this code when I console.log(this.totalCount) I only get like this enter image description here.

How to get sum of all the values?

CODE

return this.http
      .post('/media', reqBody)
      .pipe(
        map((res:IStatisticReponse) => res.data)
      ).subscribe(res => {
        this.items = res.map((r: any, i: number) => {
          r.color = this.colors[i]
          return r;
        });

        this.legendProgress = this.items.map(item => {
          return { label: item.label, color: item.color };
        });
        this.totalCount = this.items.map((item)=> item.mediaShare);
        console.log(this.totalCount)

        this.isLoading = false;
      });

Upvotes: 1

Views: 2523

Answers (2)

Philipp Meissner
Philipp Meissner

Reputation: 5482

In your current implementation you basically iterate over all items within the items array and return the objects mediaShare property.

this.totalCount = this.items.map((item)=> item.mediaShare); // => ["123", "345", ...]

What you actually want to do is to get the sum of all these values. Considering the values inside totalCount are now a collection of strings that seem to hold a numeric value, you can do the following:

this.totalCount = this.items.map((item)=> Number.parseInt(item.mediaShare)).reduce((acc, curr) => acc + curr, 0); // Or `parseFloat`, if your values might be of type float

Read up on Array.prototype.reduce to learn how it behaves.

Upvotes: 3

agung
agung

Reputation: 136

try this

let totalVal;
for(let i = 0; i < this.totalCount.length; i++) {
  totalVal = totalVal + parseInt(this.totalCount[i]);
}

Upvotes: 1

Related Questions