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
相关产品推荐
相关产品推荐

