简体   繁体   中英

Multidimensional Array: Sum Numerical Values With Same String Value

I am building a JavaScript cash register that returns change depending on what is in the cash register. This is for a freeCodeCamp challenge: https://www.freecodecamp.org/challenges/exact-change

Unfortunately I am close but stuck.

I have a function called addResult() which takes two arguments, name and val .

var result = [];
function addResult(name, val){
    result.push([name, val]);
}

So if the change required is $18 then the function will build an array like this.

[["ONE", 1.00], ["ONE", 1.00], ["ONE", 1.00], ["FIVE", 5.00], ["TEN", 10.00]]

I want the function to build it like this instead:

[["ONE", 3.00], ["FIVE", 5.00], ["TEN", 10.00]]

So I need to have unique string names but sum up the numbers but I can't work out how.

If anyone is interested in the full code, here it is:

 function checkCashRegister(price, cash, cid) { var totalCash = Math.round(calculateTotalCash()).toFixed(2); var changeDue = (cash - price) * 100; // 50 var result = []; var monies = [ {name: 'PENNY', val: 1}, {name: 'NICKEL', val: 5}, {name: 'DIME', val: 10}, {name: 'QUARTER', val: 25}, {name: 'ONE', val: 100}, {name: 'FIVE', val: 500}, {name: 'TEN', val: 1000}, {name: 'TWENTY', val: 2000}, {name: 'ONE HUNDRED', val: 10000} ]; function calculateTotalCash(){ var result = 0; for (var i = 0; i < cid.length; i++) { result = result + cid[i][1]; } return result; } function getQuantity(name){ for (var i = 0; i < cid.length; i++) { if (cid[i][0] == name) { return ((cid[i][1]) * 100) / monies[i].val; } } }; function addResult(name, val){ result.push([name, val]); } var changeCount = changeDue; // 50 var i = monies.length - 1; // 8 var result = []; while (changeCount > 0 && i > 0) { // get the number of currencies left in the drawer var quantity = getQuantity(monies[i].name); // console.log(quantity, monies[i].name); // alert(i); // if the currency is smaller then the change left and there are currencies left if (monies[i].val <= changeCount && quantity > 0) { // subtract the currency from the change changeCount = changeCount - monies[i].val; // and withdraw the money from the drawer cid[i][1] = ((cid[i][1] * 100) - monies[i].val) / 100; addResult(monies[i].name, monies[i].val); } else { // move on to the next smallest currency and try again i--; } } console.log(result); if (changeCount > 0) { return } // console.log(changeCount / 100); return changeCount; } // Example cash-in-drawer array: // [["PENNY", 1.01], // ["NICKEL", 2.05], // ["DIME", 3.10], // ["QUARTER", 4.25], // ["ONE", 90.00], // ["FIVE", 55.00], // ["TEN", 20.00], // ["TWENTY", 60.00], // ["ONE HUNDRED", 100.00]] checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]); // get the change due // loop through the change // check if the highest monie is greater than the change // if it is move on to the next lowest // when you find one that is lesser than the change subtract it from the change // if there is still leftover change required try and subtract again // check if it is higher than the change // do this untill the exact change is matched 

An easy fix would be to change the addResult function to check if the given name exists already, and if so, add the value to it

function addResult(name, val){
    let m = result.find(e => e[0] === name);
    if (m) {
        m[1] += val;
    } else {
        result.push([name, val]);
    }
}

 let result = [ ["ONE", 1.00], ["FIVE", 5.00], ["TEN", 10.00] ]; function addResult(name, val) { let m = result.find(e => e[0] === name); if (m) { m[1] += val; } else { result.push([name, val]); } } addResult("ONE", 1); console.log(result); 

A different way for sum cash :

 function SumCash(current,add) { var holder = {}; current.forEach(function (d) { if(holder.hasOwnProperty(d.name)) { holder[d.name] = holder[d.name] + d.value; } else { holder[d.name] = d.value; } }); add.forEach(function (d) { if(holder.hasOwnProperty(d.name)) { holder[d.name] = holder[d.name] + d.value; } else { holder[d.name] = d.value; } }); var obj2 = []; for(var prop in holder) { obj2.push({name: prop, value: holder[prop]}); } console.log(obj2); return obj2; } var current = [ {name: 'PENNY', value: 1}, {name: 'NICKEL', value: 5}, {name: 'DIME', value: 10}, {name: 'QUARTER', value: 25}, {name: 'ONE', value: 100}, {name: 'FIVE', value: 500}, {name: 'TEN', value: 1000}, {name: 'TWENTY', value: 2000}, {name: 'ONE HUNDRED', value: 10000} ]; var add = [ {name: 'PENNY', value: 1}, {name: 'NICKEL', value: 5}, {name: 'DIME', value: 10}, ]; SumCash(current,add); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM