Reputation: 125
I have the following array:
[Title1: 111, Title2: 222, Title3: 333]
This array is generated from a Web Socket Service and I want to accumulate the values using reduce.
I have the following code, but I can't get it to work:
this.liveDataPriceTotal = this.liveDataPrice.reduce( ( previousValue, currentValue ) => Number( previousValue ) + Number( currentValue ), 0 );
Where replacing this.liveDataPrice with [111, 222, 333] works as expected.
Any ideas how to get the accumulated total from my array?
Solution:
Since I was confused and mixed up arrays and objects, I came with the following solution which accumulates the values from my object:
this.liveDataVolume24hTotal = Object.entries( this.liveDataVolume24h ).reduce( function( total, [key, value] ) {
return ( value ? Number( total ) + Number( value ) : total );
}, 0 );
Upvotes: 1
Views: 2227
Reputation: 6007
Simple exemple:
total: number = 0;
arrayNumb: [10, 20, 30];
this.total = this.arrayNumb.reduce((a, b) => a + b);
console.log('TOTAL = ', this.total);
console: TOTAL = 60
Upvotes: 1