Reputation: 4618
I'm trying to write a JavaScript function to split a string by its delimiter ('/') and wanted to return its path combination in an array.
Input:
"Global/Europe/UK/London"
Desired Output:
["Global","Global/Europe","Global/Europe/UK"]
I tried the below recursive function, but for some reason the array contains only a single value.
function splitPath(str) {
var output = [];
if (str.lastIndexOf('/') !== -1) {
str = str.split("/").slice(0, -1).join("/");
output.push(str);
splitPath(str);
}
//console.log(output);
return output;
}
Please let me know if there's any straight way to achieve this in JavaScript.
Thanks.
Upvotes: 2
Views: 783
Reputation: 627
'Global/Europe/UK/London'
.split('/')
.map(
(item, i, items) => {
return items.slice(0, i+1).join('/');
}
)
Upvotes: 1
Reputation: 2278
Using Array#reduce
let input = "Global/Europe/UK/London";
let output = input.split("/").slice(0, -1).reduce((acc, item, index) => {
acc.push(index ? acc[index - 1] + '/' + item : item);
return acc;
}, []);
console.log(output);
Upvotes: 4
Reputation: 629
How about this ?
let output = [];
let input = str.split('/');
input.reduce((acc,v, i, arr) => { output.push(acc + "/"+ v ); return acc + "/"+ v; })
Upvotes: 1
Reputation: 39182
Here's a way to split and then iteratively add the parts:
function splitPath(str) {
const parts = str.split("/");
let head = parts.shift();
const result = [head];
for (const part of parts) {
head += "/" + part;
result.push(head);
}
return result;
}
console.log(splitPath("Global/Europe/UK/London"))
Upvotes: 1
Reputation: 386560
You could split the string and map with the parts from the beginning by using only the parts without the last one.
var string = "Global/Europe/UK/London",
grouped = string
.split('/')
.slice(0, -1)
.map(function (_, i, a) {
return a.slice(0, i + 1).join('/');
});
console.log(grouped);
Upvotes: 3