【问题标题】:Calculate the difference between last two elements in array of objects计算对象数组中最后两个元素之间的差异
【发布时间】:2022-08-03 23:53:31
【问题描述】:

我需要计算过去两个月(_id)之间的差异incometotal

{income[1]?.total} 总是给我一个固定号码:900

如何计算最后两个元素之间的total 差异?

注意:res.data 已按_id 排序。

const [income, setIncome] = useState([]);
  const [perc, setPerc] = useState(0);
  useEffect(() => {
    const getIncome = async () => {
      try {
        const res = await userRequest.get(\"orders/income\");
        const sort = res.data.sort((x, y) => x._id - y._id)
        setIncome(sort);
        setPerc((res.data[1].total * 100) / res.data[0].total - 100);
        console.log(sort);
      } catch {}
    };
    getIncome();
  }, []);

return(
  <div>{income[1]?.total} $</div>
)

这是我的 console.dev:

0: {_id: 6, total: 448}
1: {_id: 7, total: 900}
2: {_id: 8, total: 100}
3: {_id: 9, total: 700}
4: {_id: 10, total: 990}
5: {_id: 11, total: 20}
6: {_id: 12, total: 20}

    标签: javascript reactjs


    【解决方案1】:
    const difference = sort[sort.length - 1].total - sort[sort.length -2].total;
    

    这将为您提供排序数组中最后两个元素的总道具之间的差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多