Sonny Hansen
Sonny Hansen

Reputation: 630

Sum of Array with filter and reduce

i'm trying to get the total of all my products in my list.

this.totalValue = this.items.filter((item) => item.qtyvalue)
                            .map((item) => item.qtyvalue)
                            .reduce((sum, current) => sum + current)

This is almost working as it gives me 650.00110.0030175.0050.00

But i want the numbers added together, how do i do this?

kind regards

Upvotes: 1

Views: 3723

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68645

I think, your qtyvalue-s are strings, not numbers, so you get just them concatenated as strings. In the map function use parseFloat.

this.totalValue = this.items.filter(item => item.qtyvalue)
                            .map(item => parseFloat(item.qtyvalue))
                            .reduce((sum, current) => sum + current)

Upvotes: 0

santosh singh
santosh singh

Reputation: 28652

It's looks like your quantity is string not a number.You can try following code snippet

this.totalValue = this.items.filter((item) =>item.qtyvalue)
                            .map((item) => +item.qtyvalue)
                            .reduce((sum, current) => sum + current);
console.log(this.totalValue);

WORKING DEMO

Upvotes: 4

Related Questions