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:
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);