You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对接口返回的res.data按_id字段进行排序?

按_id字段排序res.data的解决方案

你可以利用JavaScript的Array.sort()方法对返回的res.data按_id字段进行排序,注意先复制原数组避免直接修改源数据,再执行排序操作:

修改后的代码

const [income, setIncome] = useState([]);
const [perc, setPerc] = useState(0);
useEffect(() => {
  const getIncome = async () => {
    try {
      const res = await userRequest.get("orders/income");
      // 按_id升序排序(需降序则改为b._id - a._id)
      const sortedData = [...res.data].sort((a, b) => a._id - b._id);
      setIncome(sortedData);
      // 基于排序后的数组计算perc
      setPerc((sortedData[1].total * 100) / sortedData[0].total - 100);
      console.log(sortedData);
    } catch {}
  };
  getIncome();
}, []);

关键说明

  • [...res.data]:通过扩展运算符复制原数组,避免直接修改res.data的原始引用
  • .sort((a, b) => a._id - b._id):通过比较_id的数值差实现升序排序;切换为b._id - a._id即可得到降序结果
  • 计算perc时使用排序后的sortedData,确保基于有序数组完成计算

排序后你的数组会呈现如下有序状态:

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}

内容的提问来源于stack exchange,提问作者Darkpsinight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:06:25