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

JavaScript如何筛选目录树数组中的叶子节点路径

实现思路

路径对应的节点如果是叶子节点,就不会存在其他更长的路径以它作为父级前缀。我们只需要过滤出数组中没有其他路径以当前路径+\为前缀的元素即可。

实现代码

let arr = [
  '0',
  '2',
  '0\\0-1',
  '2\\2-0',
  '2\\2-0\\2-0-0',
  '2\\2-0\\2-0-0\\2-0-0-0',
  '2\\2-0\\2-0-0\\2-0-0-1'
]

const getLeafPaths = (pathArr) => {
  return pathArr.filter(currentPath => {
    // 拼接父级前缀标记,避免短路径名误匹配为其他不相关长路径的前缀
    const parentPrefix = currentPath + '\\'
    return !pathArr.some(otherPath => otherPath.startsWith(parentPrefix))
  })
}

const newArr = getLeafPaths(arr)
console.log(newArr)

注:如果你的路径使用/作为分隔符,只需要把代码中拼接的\\替换为/即可适配。

输出结果

[
  '0\\0-1',
  '2\\2-0\\2-0-0\\2-0-0-0',
  '2\\2-0\\2-0-0\\2-0-0-1'
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:27:06