从路径数组中递归移除包含子目录的父目录
Filter Paths to Keep Only Deepest Directories
Got it, let's solve this problem! You need to take an array of file system paths and strip out any parent directories that have child directories present in the array—leaving only the deepest, most specific paths. Here's a straightforward approach using JavaScript:
Step-by-Step Solution
First, we need to handle path consistency (like trailing slashes) to avoid false mismatches, then use a set for quick lookups to check if a path has any children in the array.
Code Implementation
function keepDeepestPaths(paths) { // Standardize paths: ensure they all end with a slash for consistent matching const standardizedPaths = paths.map(path => { return path.endsWith('/') ? path : `${path}/`; }); // Create a set for O(1) lookups to optimize performance const pathSet = new Set(standardizedPaths); // Filter paths: keep only those with no child paths in the set return standardizedPaths.filter(path => { // Check if any other path starts with this path (and isn't identical) return !Array.from(pathSet).some(otherPath => { return otherPath !== path && otherPath.startsWith(path); }); }).map(path => { // Optional: remove trailing slash to match your desired output format return path.endsWith('/') ? path.slice(0, -1) : path; }); } // Example usage with your sample paths const originalPaths = [ '/root/', '/root/folder1/', '/root/folder1/folder4/', '/root/folder2', '/root/folder2/folder3', '/root/folder2/folder3/folder5', '/root/folder6' ]; const deepestPaths = keepDeepestPaths(originalPaths); console.log(deepestPaths); // Output: ["/root/folder1/folder4", "/root/folder2/folder3/folder5", "/root/folder6"]
How It Works
- Path Standardization: We add a trailing slash to every path so that we don't get false matches (like
/root/folder2incorrectly matching/root/folder2other). This ensures parent-child relationships are detected reliably. - Fast Lookups: Using a Set lets us check the existence of paths in constant time, which makes the solution efficient even for large arrays of paths.
- Filter Logic: For each path, we check if there's any other path in the set that starts with it (but isn't the same path). If such a path exists, the current one is a parent directory and gets discarded. If not, it's a deepest path and we keep it.
- Formatting Cleanup: The final
mapstep removes the trailing slash if you want to match the exact output format you specified.
This approach handles edge cases like mixed trailing slashes, works for any directory depth, and is easy to adjust if you need case-insensitive matching (just add .toLowerCase() during standardization).
内容的提问来源于stack exchange,提问作者Zvonimir Rudinski
相关产品推荐
相关产品推荐

