简体   繁体   中英

How to calculate total using Javascript/ TypeScript reduce

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 );

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

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