Reputation: 1294
I need a little help with this as it's making my brain hurt.
Here is a string I have:
var path = "/great-grand-parent/grand-parent/parent/";
And an array from that:
var pathsArray = path.split("/");
After splitting that string on "/" into an array so each level stands on its own, I would like to build another array where each index of pathsArray[] is used to construct an array that would contain full paths of all parents:
0: /great-grand-parent/grand-parent/parent/
1: /great-grand-parent/grand-parent/
2: /great-grand-parent/
3: /
I tried using a for loop to loop backwards through pathsArray[] but then got confused on how to reference each index recursively. Any help would be greatly appreciated! Probably pretty simple.
Upvotes: 0
Views: 13
Reputation:
var result = pathsArray.map(function(s, i, arr) {
return arr.slice(0, arr.length-i).join("/") || "/";
});
var path = "/great-grand-parent/grand-parent/parent/";
var pathsArray = path.split("/");
var result = pathsArray.map(function(s, i, arr) {
return arr.slice(0, arr.length-i).join("/") || "/";
});
document.body.innerHTML = "<pre>" + JSON.stringify(result, null, 2) + "</pre>";
There's an extra result because of the trailing /
. You can trim that away if you want.
Upvotes: 1