1

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 );
4
  • 1
    Do you have an array, or an object? Commented Mar 15, 2018 at 16:36
  • It is initialized as: liveDataPrice: number[] = []; and the values are added as: this.liveDataPrice[data['MARKET']] = data['PRICE']; Commented Mar 15, 2018 at 16:57
  • @jonrsharpe: Variable this.liveDataPrice is an object. Commented Mar 15, 2018 at 17:23
  • [Title1: 111, Title2: 222, Title3: 333] is an array of objects Commented Apr 19, 2018 at 15:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.