【问题标题】:how do i sum duplicate array elements我如何对重复的数组元素求和
【发布时间】:2019-06-29 06:14:41
【问题描述】:

该程序运行良好,除了“更改”数组有许多重复项,对重复项求和应该很容易,但它给出了错误的总和! 例如:将 3 个 20 相加应该是 60,而不是 80! 我注意到该错误仅发生在奇数重复项中! 我无法弄清楚的另一件事是为什么当我对重复项求和时“更改”数组会发生变化?我将更改数组复制到另一个数组,所以如果第二个数组发生任何事情,它不应该影响“更改”数组!

程序运行良好,直到我到达需要对重复项求和的部分(sumDuplicates() 函数本身可以正常工作,但不适用于我的代码)

function checkCashRegister(price, cash, cid) {
  var change = [];
  let difference = cash - price;
  let level = 0;
  let currency = [
    ["PENNY", 0.01],
    ["NICKEL", 0.05],
    ["DIME", 0.1],
    ["QUARTER", 0.25],
    ["ONE", 1],
    ["FIVE", 5],
    ["TEN", 10],
    ["TWENTY", 20],
    ["ONE HUNDRED", 100]
  ]
  //sum all money in register
  let totalFunds = cid.reduce((r, [key, value]) => {
    return r + value
  }, 0)

  //function to match the difference to appropriate currency
  function findLevel(dif) {
    for (let i = currency.length - 1; i >= 0; i--) {
      //our change must be the highest availabe currency
      if (dif >= currency[i][1] && cid[i][1] != 0) {
        //console.log(currency[i])
        return i
      }
    }
  }
  //function to subtract
  function subtractor(dif, lvl) {
    if (cid[lvl][1] != 0) {
      dif = dif.toFixed(2)
      dif = dif - currency[lvl][1]
      cid[lvl][1] -= currency[lvl][1]
      change.push(currency[lvl])
      return dif
    }
  }
  //if no change needed
  if (difference == 0) {
    return {
      status: "CLOSED",
      change: []
    }
  }
  //if we dont have enough money to pay back
  if (totalFunds < difference) {
    return {
      status: "INSUFFICIENT_FUNDS",
      change: []
    }
  }
  //if we need to pay change AND we have enough money
  if (difference > 0 && totalFunds >= difference) {
    while (difference >= 0.01) {
      level = findLevel(difference)
      difference = subtractor(difference, level)
      //console.log(difference)
    }
  }

  //to sum duplicate elements in the "change" array, this is the problem!!!
  function sumDuplicates(arr1) {
    let arr = [...arr1]
    let sums = arr.reduce((sums, item) => {
      let found = sums.find(([key]) => key === item[0]);
      //console.log(found)
      if (found)
        found[1] += item[1];
      else
        sums.push(item);
      // console.log(item)
      return sums;
    }, []);
    return sums;
  }
  let sums = sumDuplicates(change)
  console.log(sums);
  return {
    status: "OPEN",
    change: sums
  };
}

checkCashRegister(3.26, 100, [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
]);

我期望[[twenties,60]] 而不是我得到[[twenties,80]]

【问题讨论】:

  • @Bosco 代码已经使用 sn-p 编辑器的 Tidy 功能缩进了。为什么需要去掉 sn-p 来修复缩进?
  • 编辑同时发生。需要回滚或重复

标签: javascript arrays sum filtering


【解决方案1】:

您需要小心将引用推入数组,因为它们不会复制。您在几个地方执行此操作,并且在您的 sum 函数中,您最终会修改原始数组,这会更改查找表中的值。

if (found)
     found[1] += item[1]; // <-- now modifying your original currency lookup!
else
     sums.push(item);     // <-- your pushing a ref to your original currency lookup!

快速解决方法是在 sum 函数中推送副本:

 sums.push([...item])

一种(可能是更好的选择)是将副本推送到change 数组中:

function subtractor(dif, lvl) {
  if (cid[lvl][1] != 0) {
      dif = dif.toFixed(2)
      dif = dif - currency[lvl][1]
      cid[lvl][1] -= currency[lvl][1]
      change.push([...currency[lvl]]) // < push a copy not the original ref
      return dif
   }
 }

function checkCashRegister(price, cash, cid) {
  var change = [];
  let difference = cash - price;
  let level = 0;
  let currency = [
    ["PENNY", 0.01],
    ["NICKEL", 0.05],
    ["DIME", 0.1],
    ["QUARTER", 0.25],
    ["ONE", 1],
    ["FIVE", 5],
    ["TEN", 10],
    ["TWENTY", 20],
    ["ONE HUNDRED", 100]
  ]
  //sum all money in register
  let totalFunds = cid.reduce((r, [key, value]) => {
    return r + value
  }, 0)

  //function to match the difference to appropriate currency
  function findLevel(dif) {
    for (let i = currency.length - 1; i >= 0; i--) {
      //our change must be the highest availabe currency
      if (dif >= currency[i][1] && cid[i][1] != 0) {
        //console.log(currency[i])
        return i
      }
    }
  }
  //function to subtract
  function subtractor(dif, lvl) {
    if (cid[lvl][1] != 0) {
      dif = dif.toFixed(2)
      dif = dif - currency[lvl][1]
      cid[lvl][1] -= currency[lvl][1]
      change.push([...currency[lvl]])  //< -- PUSH A COPY!
      return dif
    }
  }
  //if no change needed
  if (difference == 0) {
    return {
      status: "CLOSED",
      change: []
    }
  }
  //if we dont have enough money to pay back
  if (totalFunds < difference) {
    return {
      status: "INSUFFICIENT_FUNDS",
      change: []
    }
  }
  //if we need to pay change AND we have enough money
  if (difference > 0 && totalFunds >= difference) {
    while (difference >= 0.01) {
      level = findLevel(difference)
      difference = subtractor(difference, level)
      //console.log(difference)
    }
  }

  //to sum duplicate elements in the "change" array, this is the problem!!!
  function sumDuplicates(arr1) {
    let arr = [...arr1]
    let sums = arr.reduce((sums, item) => {
      let found = sums.find(([key]) => key === item[0]);
      //console.log(found)
      if (found)
        found[1] += item[1];
      else
        sums.push(item);  
      // console.log(item)
      return sums;
    }, []);
    return sums;
  }
  let sums = sumDuplicates(change)
  console.log(sums);
  return {
    status: "OPEN",
    change: sums
  };
}

console.log(checkCashRegister(3.26, 100, [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多