Files
2026-07-13 21:36:17 +08:00

1.4 KiB

title, impact, impactDescription, tags
title impact impactDescription tags
使用 flatMap 在一次遍历中完成映射与过滤 LOW-MEDIUM 消除中间数组 javascript, arrays, flatMap, filter, performance

使用 flatMap 在一次遍历中完成映射与过滤

影响程度:LOW-MEDIUM(消除中间数组)

链式调用 .map().filter(Boolean) 会创建一个中间数组并迭代两次。使用 .flatMap() 可以在一次遍历中同时完成转换和过滤。

不正确的做法(2 次迭代,存在中间数组):

const userNames = users
  .map(user => user.isActive ? user.name : null)
  .filter(Boolean)

正确的做法(1 次迭代,无中间数组):

const userNames = users.flatMap(user =>
  user.isActive ? [user.name] : []
)

更多示例:

// 从响应中提取有效邮箱
// 之前
const emails = responses
  .map(r => r.success ? r.data.email : null)
  .filter(Boolean)

// 之后
const emails = responses.flatMap(r =>
  r.success ? [r.data.email] : []
)

// 解析并过滤有效数字
// 之前
const numbers = strings
  .map(s => parseInt(s, 10))
  .filter(n => !isNaN(n))

// 之后
const numbers = strings.flatMap(s => {
  const n = parseInt(s, 10)
  return isNaN(n) ? [] : [n]
})

适用场景:

  • 在转换元素的同时过滤掉部分元素
  • 条件映射,部分输入不产生输出
  • 解析/验证时需跳过无效输入