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

如何过滤数组中undefined值并同步删除另一数组对应索引的元素

最简实现方案

直接对两个数组分别过滤即可,不需要额外存储删除索引:

// 过滤nums数组,保留非undefined值
const newNums = nums.filter(item => item !== undefined)
// 过滤steps数组,仅保留nums同位置不为undefined的元素
const newSteps = steps.filter((_, index) => nums[index] !== undefined)

这个写法逻辑清晰,代码量极少,处理后得到的结果和你给出的预期输出完全一致。


如果需要处理超大数组、想要一次遍历完成操作(性能更优),可以用合并配对再拆分的写法:

const [newSteps, newNums] = steps.reduce((result, step, index) => {
  const num = nums[index]
  if (num !== undefined) {
    result[0].push(step)
    result[1].push(num)
  }
  return result
}, [[], []])

一次遍历就能同时完成过滤和拆分,适合数组长度极大的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:36:05