-1

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) => {
  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;
Kyle Underhill
  • 89
  • 15
  • 43

1 Answers1

1

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

BTSM
  • 1,585
  • 8
  • 12
  • 26