【问题标题】:Map and filter in one method?用一种方法映射和过滤?
【发布时间】:2022-07-06 15:04:22
【问题描述】:

以下代码处理文件路径列表,并且应该只返回 XML 文件的文件名(不带扩展名)。目前我得到了这个:

const filteredFiles = files
  .map(f => f.match(/.*\/(.*)\.xml/)) // map to regex match with capture
  .filter(v => v)                     // non-matches returned null and will be filtered out here
  .map(m => m[1])                     // map out the regex capture

我觉得这段代码很麻烦。有没有办法以更“有效”的方式结合匹配和过滤? “高效”是指代码可读高效而不是时间高效,因为输入数组最多保存 100 个值,但大部分时间在 10 到 20 之间。

【问题讨论】:

  • 使用 foreach 并将更改的元素推送到 foreach 中的过滤文件可能是您想要的。我认为它的代码可读性更高。
  • 如果正在寻找这种方式来优化您的代码,或者它应该只迭代一次。所以你可以使用.reduce 示例files.reduce((r, f) => { const value = f.match(/.*\/(.*)\.xml/); if (value?.[1]) { return [...r, value[1]]} return r;},[])

标签: javascript arrays ecmascript-6


【解决方案1】:

你可以(ab)使用flat map:

const filteredFiles = files.flatMap((f)=>{
  let match = f.match('...');
  if (match) {
      return [match[1]]
  } else {
      return []
  }
})

不确定它是否真的比原版更好。

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 2022-08-16
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2018-07-26
    • 2017-12-22
    相关资源
    最近更新 更多