I would like to get the max of each type of bill using the reduce method. The function has to itirate and compare each item to the next in line, then if the names match(item[0]) it should compare their values (item[1]) and store the biggest value with that original name.
I want to use reduce for this but am struggling to understanding how exactly accumulator is being applied here. Any suggestions? :)
const tempCollected= [
["TWENTY", 20],
["TWENTY", 40],
["TWENTY", 60],
["TEN", 10],
["TEN", 20],
["FIVE", 5],
["FIVE", 10],
["FIVE", 15],
["ONE", 1],
["QUARTER", 0.25],
["QUARTER", 0.5],
["DIME", 0.1],
["DIME", 0.2],
["PENNY", 0.01],
["PENNY", 0.02],
["PENNY", 0.03]
]
/* Desired outcome using reduce
[
["TWENTY", 60],
["TEN", 20],
["FIVE", 15],
["ONE", 1],
["QUARTER", 0.5],
["DIME", 0.2],
["PENNY", 0.03]
]
*/
/*My try */
const attempt=tempCollected.reduce(
(a,b,i,arr)=>{
if(b[i+1][0]===b[0]){ //if next item has the same name as the current
return [...a,b[0],Math.max(b[1],b[i+1][1])] //return Math.max(...of those two) + the original name of the bill
}
return [...a,b]
},[]
)