Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to keep only the paths to the leaves in a directory tree?

I have this array of directory paths (strings):

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'
]

The trees of directories would look like this (note that 0-1, 2-0-0-0, and 2-0-0-1 are the leaves):

0
|_ 0-1

2
|_ 2-0
   |_ 2-0-0
      |_ 2-0-0-0
      |_ 2-0-0-1

From this array, I want to keep only the paths to the leaves. This means that I want to remove all elements, except 0\0-1, 2\2-0\2-0-0\2-0-0-0, and 2\2-0\2-0-0\2-0-0-1. My new array should look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

newArr = [
  '0\\0-1',
  '2\\2-0\\2-0-0\\2-0-0-0',
  `2\\2-0\\2-0-0\\2-0-0-1`
]

How can I do this in JavaScript?

>Solution :

Suggested by DexieTheSheep, using startsWith

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 result = arr.filter(item => !arr.some(ex => ex.startsWith(item + '\\')));

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading