多维数组:具有相同字符串值的和数值

时间:2017-09-04 21:28:23

标签: javascript arrays multidimensional-array

我正在构建一个JavaScript收银机,它根据收银机中的内容返回更改。这适用于freeCodeCamp挑战:https://www.freecodecamp.org/challenges/exact-change

不幸的是,我很接近而且卡住了。

我有一个名为addResult()的函数,它有两个参数,nameval

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

因此,如果所需的更改是18美元,那么该函数将构建一个这样的数组。

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

我希望函数能够像这样构建它:

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

所以我需要有唯一的字符串名称,但总结数字,但我无法弄清楚如何。

如果有人对完整代码感兴趣,请点击:

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

2 个答案:

答案 0 :(得分:1)

一个简单的解决方法是更改​​addResult函数以检查给定名称是否已存在,如果存在,则将值添加到其中

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);

答案 1 :(得分:0)

总和现金的另一种方式:

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);