How do I use map reduce to total the 2nd property of an array

This is an early step in the Cash Register Challenge at Free Code Camp, I think I’ve got ahead of the curriculm a bit, but I was also hoping most of it would be review. I thought I could start preplanning my projects with psuedo code.
I’m just trying to make a variable that would take the 2nd property of the array and sum a total to represent how much is in the drawer at the moment

let cid = [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]
var totalINdrawer = [cid]; //reduce the 2nd property of an arrary

var myData = reduce.cid[i][1];
console.log(myData);

It is an array of arrays, where the main array contains currency and the inner array is the name and amount.

To gain a total, you can use reduce to achieve that, and before that use map to get just the amounts.

var total = cid.map(currency => currency[1])
    .reduce((total, amount) => total + amount);
1 Like

…that returns $335.40999999999997? The cents should add up to .41 I guess it’s some sort of rounding error since we’re already operating behind the decimal. Should I just round it up? Or should I try to correct for it somewhere sooner in the process? I’d like to understand more about where the anomaly starts… If I started by multiplying them all by 100 then divided afterwords, would that correct for it? Or is that most likely what it’s already doing and where the anomaly starts at?

Avoiding Problems with Decimal Math in JavaScript

This link implies I was on the correct path. I should probably multiply all the cents by 100 to be working with whole numbers, I should probably do that in the mapping phase before the reduction takes place.

let cid = [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]
var total = cid.map(currency => currency[1]*100)
    .reduce((total, amount) => total + amount);
console.log(total);
total = total/100;
console.log(total);

ok, this is getting me the number I was hoping for, thank you for pointing me in the right direction

1 Like

Or, you could do it the first way and round it using .toFixed(2).

Just my two cents.

V/r,

^ _ ^

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.