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

JavaScript数组filter过滤后如何重置元素内的index属性计数

解决方案

filter 仅负责过滤符合条件的元素,不会修改元素内部属性,你可以在过滤后链式调用 map 方法,利用 map 回调的第二个参数(新数组的当前索引)重置元素的index属性即可。

推荐写法(不修改原数组元素,无副作用)

let array = [
  {a: "hi", index: 0},
  {a: "hi1", index: 1},
  {a: "hi2", index: 2},
  {a: "hi3", index: 3},
  {a: "hi4", index: 4},
  {a: "hi5", index: 5},
  {a: "hi6", index: 6}
]

const result = array
  .filter((i, index) => index > 3)
  .map((item, newIndex) => ({...item, index: newIndex}))

执行后result的值就是你需要的结果:

[
  {a: "hi4", index: 0},
  {a: "hi5", index: 1},
  {a: "hi6", index: 2}
]

可选写法(会修改原数组的元素,仅适用于确定不需要保留原数据的场景)

const result = array
  .filter((i, index) => index > 3)
  .map((item, newIndex) => {
    item.index = newIndex
    return item
  })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 06:03:04