如何过滤数组中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
相关产品推荐
相关产品推荐

