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

如何将filter函数中获取的原数组索引传递到后续map函数中

解决方案

核心逻辑:在过滤操作前绑定原数组索引与对应条目,避免过滤后索引偏移丢失原始信息。

常规实现方案

普通业务场景下直接使用该方案即可,逻辑清晰易维护:

{itemArray
  // 先将原数组条目和对应原始索引绑定
  .map((item, originIndex) => ({ item, originIndex }))
  // 过滤逻辑和原有逻辑一致,仅判断条目类型是否匹配
  .filter(({ item }) => item.type === compItem.type)
  // 渲染时直接取用绑定好的原始索引
  .map(({ item, originIndex }) => {
    return (
      <Row>
        <Col key={item.name} onClick={(e) => openItemEdit(e, originIndex, item)} >
          {item.name} 
        </Col>
      </Row>
    );
  })}

极致性能优化方案

如果处理的数组长度超过十万级,可通过一次reduce同时完成索引绑定和过滤,省去一次遍历步骤:

{itemArray.reduce((resultList, item, originIndex) => {
  if (item.type === compItem.type) {
    resultList.push({ item, originIndex })
  }
  return resultList
}, []).map(({ item, originIndex }) => {
  return (
    <Row>
      <Col key={item.name} onClick={(e) => openItemEdit(e, originIndex, item)} >
        {item.name} 
      </Col>
    </Row>
  );
})}

方案优势:

  • 无需后续遍历原数组查找对应条目,直接通过原始索引操作原数组,执行效率更高
  • 避免了存在相同属性值的条目时,查找匹配出现错误的问题
  • 无额外临时变量存储待编辑条目,代码维护成本更低

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:24:07