0

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.

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect! Thank you very much for your help. Pretty efficient way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.