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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.