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

React Native中如何根据指定ID数组计算对应数据的value总和?

计算指定ID对应元素的value总和

这里提供两种实用的实现方式,帮你完成需求:

方式一:直接用reduce累加(适合小数据量场景)

const getTotalValue = (data, targetIds) => {
  return data.reduce((sum, item) => {
    // 校验当前元素ID是否在目标数组中,同时把字符串类型的value转为数字
    if (targetIds.includes(item.id)) {
      sum += Number(item.value);
    }
    return sum;
  }, 0);
};

// 调用函数
const total = getTotalValue(data, ids);
console.log(total); // 输出结果:21000

方式二:用Set优化查找效率(适合大数据量场景)

如果你的data数组元素较多,用Set存储目标ID能大幅提升查找速度(Set.has()的时间复杂度为O(1),比数组的includes()更高效):

const getTotalValue = (data, targetIds) => {
  const idSet = new Set(targetIds);
  return data.reduce((sum, item) => {
    if (idSet.has(item.id)) {
      sum += Number(item.value);
    }
    return sum;
  }, 0);
};

// 调用示例
const total = getTotalValue(data, ids);
console.log(total); // 输出结果:21000

关键注意事项

  • 原数据中的value是字符串类型,必须用Number()或parseInt()转为数字后再累加,否则会触发字符串拼接(比如"1000"+"5000"会得到"10005000"而非6000)
  • 如果担心value存在非数字内容,可以添加容错处理:sum += Number(item.value) || 0,避免出现NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:30:55