Search code examples
javascriptarraysfilteringpseudocode

Removing parent directories from array



Suppose I have a folder structure like this:

  • Root
    • Folder1
      • Folder 4
    • Folder2
      • Folder3
        • Folder5
    • Folder 6

I've got an array containing all the paths:

let paths = ['/root/','/root/folder1/','/root/folder2','/root/folder2/folder3'...

What I would like to accomplish is to remove the parent directories which have children recursively so I'd end up with this:

let paths = ['/root/folder1/folder4','/root/folder2/folder3/folder5','/root/folder6'];

Don't worry this isn't for homework or anything, just me getting stuck on my personal project :D
If you can answer with pseudocode (or even better JavaScript) that would be cool.


Solution

  • You could check if the array contains some string which starts with the given path. Then filter that item out.

    var paths = ['/root/', '/root/folder1/', '/root/folder2', '/root/folder2/folder3/', '/root/folder1/folder4', '/root/folder2/folder3/folder5'],
        result = paths.filter((p, i, a) => !a.slice(i + 1).some(o => o.startsWith(p)));
        
    console.log(result);