'React how to sum numbers from a map function?

How can i sum numbers out of a map function? I'm getting all the prices for each month in form of numbers. Im getting just single numbers, not an Array from my mapping function so i can't use reduce function

Edit: Posted all code now i hope it helps to understand it better now. This is what i get when i show carttotal. It's shown for the correct month but not as a sum [Current output][1]

const PayFees = () => {
  const [history, setHistory] = useState([]);
  const token = useSelector((state) => state.token);
  useEffect(() => {
    const getHistory = async () => {
      const res = await axios.get('/api/payment', {
        headers: { Authorization: token },
      });
      setHistory(res.data);
    };
    getHistory();
  }, [token, setHistory]);

  const sum = history
    .map((order) => order.carttotal)
    .reduce((prev, curr) => prev + curr, 0);

  const getYears = new Set(
    history.map((date) => {
      const year = dayjs(date.createdAt).format('YYYY');
      return year;
    })
  );
  const getMonths = new Set(
    history.map((date) => {
      const monthYear = dayjs(date.createdAt).format('MM/YYYY');
      return monthYear;
    })
  );

  const yearsArr = [...getYears];
  const monthArr = [...getMonths];
  return (
    <div>
      <div>
        {yearsArr.map((year) => {
          return (
            <div>
              <div>{year}</div>
              <div>
                {monthArr.map((month) => {
                  return dayjs(month, 'MM/YYYY').format('YYYY') === year ? (
                    <div>
                      {month}
                      {history.map((order) => {
                        console.log(order);
                        return dayjs(order.createdAt).format('MM/YYYY') ===
                          month ? (
                          <div>{order.carttotal}</div>
                        ) : (
                          ''
                        );
                      })}
                    </div>
                  ) : (
                    ''
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default PayFees;
```


  [1]: https://i.stack.imgur.com/Qvb5A.png


Solution 1:[1]

Maybe its a ugly solution and way to long but im happy i finally found a solution. I crated a new component and with the code below everything works

{yearsArr.map((year) => {
          return (
            <div>
              <div>{year}</div>
              <div>
                {monthArr.map((month) => {
                  return dayjs(month, 'MM/YYYY').format('YYYY') === year ? (
                    <>
                      {month}
                      <MonthlyFee date={month} />
                    </>
                  ) : (
                    ''
                  );
                })}
              </div>
            </div>
          );
        })}

MonthlyFee component:

const MonthlyFee = ({ date }) => {
  const [history, setHistory] = useState([]);
  const token = useSelector((state) => state.token);
  useEffect(() => {
    const getHistory = async () => {
      const res = await axios.get('/api/payment');
      setHistory(res.data);
    };
    getHistory();
  }, [token, setHistory]);

  const getMonthlyOrder = history.map((order) => {
    const monthlyOrder =
      date === dayjs(order.createdAt).format('MM/YYYY')
        ? order
        : { carttotal: 0 };
    return monthlyOrder;
  });

  const final = getMonthlyOrder
    .map((order) => order.carttotal)
    .reduce((prev, curr) => prev + curr, 0);

  return <div>{final}</div>;
};

export default MonthlyFee;

Solution 2:[2]

I'm sure there are other ways, but you could try this:

const [total, setTotal] = useState(0)

{history.map((order) => {
setTotal(total + order.carttotal)}}

Then call {total} wherever you need it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zut4too
Solution 2 Gordon Maloney