Nathan
Nathan

Reputation: 58

Javascript reduce to produce a total cost not working

I'm attempting to output a total cost based off the totals but can't seem to get this functioning as intended with the .reduce method.

I build a "costs" array up which looks like this:

const costs = ["5.50", "1.00", "2.00", "1.50"]

I then attempt to assign a variable called totalCost to the totals (have tried various ways with the parseFloat().toFixed(2) methods but not having the desired outcome.

// Returns prev is not defined (2nd instance)
const totalCost = costs.reduce((prev, current, index) => prev, parseFloat(prev + current).toFixed(2), 0);

// Returns prev is not defined due to mismatch of values associated to the arguments
const totalCost = costs.reduce((prev, current, index) => prev + parseFloat(current).toFixed(2), 0);

The result is always either 5.50 (the first value in the array) or a string which attaches them all.

Have also tried forEach. and a straight + of the values with a parseFloat().toFixed(2)

Any points in the right direction would be appreciated as I feel it's almost there, but I've been banging my head against a wall for the last hour or so.

Upvotes: 0

Views: 185

Answers (1)

Patrick Mascari
Patrick Mascari

Reputation: 763

Your problem with your first attempt costs.reduce((prev, current, index) => prev, parseFloat(prev + current).toFixed(2), 0);

is that the language has no way of distinguishing the comma on prev, as the end of the function or the end of the argument. It thus thinks parseFloat... is the next argument to your reduce function.

Your second issue is that toFixed returns a string.

How about:

costs.reduce((prev, current, index) => prev + parseFloat(current), 0).toFixed(2)

Upvotes: 2

Related Questions