求数组中的数值

huangapple go评论60阅读模式
英文:

Sum values in array

问题

以下是代码部分的翻译:

const App = (props) => {
  let array = [
    {
      amount: "12",
      amount2: "0",
      type: "Purchased"
    },
    {
      amount: "0",
      amount2: "34",
      type: "Donation"
    }
  ];

  const total = (data) => {
    let tempSub = [];
    let sum;
    if (data.length > 0) {
      data.map((i, k) => {
        let productTotal = i.amount;
        let donationTotal = i.amount2;
        tempSub.push(i.type === "Purchased" ? productTotal : donationTotal);
      });
      sum = tempSub.reduce(function (a, b) {
        return a + b;
      }, 0);
    } else {
      sum = 0;
    }
    return sum;
  };
  return (
    <>
      {array.length > 0
        ? array.map((item, i) => {
            return <>{total(item)}</>;
          })
        : ""}
    </>
  );
};

export default App;

请注意,这是代码的翻译,只包括代码本身,没有其他内容。

英文:

I am trying to get the values in the array based on their type and then sum everything at total(item). The result returns concatenated values instead of a sum.

const App = (props) =&gt; {
  let array = [
    {
      amount: &quot;12&quot;,
      amount2: &quot;0&quot;,
      type: &quot;Purchased&quot;
    },
    {
      amount: &quot;0&quot;,
      amount2: &quot;34&quot;,
      type: &quot;Donation&quot;
    }
  ];

  const total = (data) =&gt; {
    let tempSub = [];
    let sum;
    if (data.length &gt; 0) {
      data.map((i, k) =&gt; {
        let productTotal = i.amount;
        let donationTotal = i.amount2;
        tempSub.push(i.type === &quot;Purchased&quot; ? productTotal : donationTotal);
      });
      sum = tempSub.reduce(function (a, b) {
        return a + b;
      }, 0);
    } else {
      sum = 0;
    }
    return sum;
  };
  return (
    &lt;&gt;
      {array.length &gt; 0
        ? array.map((item, i) =&gt; {
            return &lt;&gt;{total(item)}&lt;/&gt;;
          })
        : &quot;&quot;}
    &lt;/&gt;
  );
};

export default App;

答案1

得分: 1

返回在reduce回调函数中的parseInt(a) + parseInt(b)。

英文:

Please return parseInt(a) + parseInt(b) in reduce callback function

huangapple
  • 本文由 发表于 2023年2月18日 13:55:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定