0

I want to achieve the following:

Given: A string like 'path1.path2.path3';

Wanted result: A list of strings -> [path1, path1.path2, path1.path2.path3];

The order has to be the same, I just need all the "levels". I need this to create a breadcrumb-component for an Angular-Applikation using ui-router. States do have names like "path1.path2", which means path2 is a child of path1.

The problem for me is not the splitting, I know how to achieve that via split. My problem is merging them again like mentioned above.

My first idea was to use array.split to get the single parts of the string. But I'm not sure how to build the loop to add a single partial in each iteration.

Vortilion
  • 406
  • 2
  • 6
  • 24

4 Answers4

1

Seems like this does what you want:

'path1.path2.path3'
  .split('.')
  .map((section, i, arr) => [...arr.slice(0, i), section].join('.'));

It splits the strings into sections using . as the delimiter, then for each section, it joins it together with all previous sections, using . as the delimiter.

Aurast
  • 3,189
  • 15
  • 24
  • Awesome, thanks! I also found a solution which looks a lot more complicated than yours: this.breadcrumb = this.router.globals.current.data.breadcrumb; // path1.path2.path3 this.breadCrumbPartials = this.breadcrumb.split('.'); // [path1,path2,path3] this.stateList = []; let state = ''; for(let i = 0; i < this.breadCrumbPartials.length; i++) { if(i > 0) { state = state + '.'; } state = state + this.breadCrumbPartials[i]; this.stateList.push(state); } – Vortilion Dec 29 '22 at 14:47
1

Try using a reducer for the splitted string. Something like:

const str = "path1.path2.path3";

console.log( str.split(".").reduce( (acc, str, i) => 
  [...acc, (i ? `${acc[i - 1]}.${str}` : str)], []) );
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

There are already some answers here, but i'd like to add mine with reduce:

const string = 'path1.path2.path3'

const paths = string.split('.')

const res = paths.reduce((acc, curr) => [...acc, `${acc[acc.length-1] ? acc[acc.length-1] + '.' : ''}${curr}`], [])

console.log(res)
Damzaky
  • 6,073
  • 2
  • 11
  • 16
0

You could get the position of the dots and slice the array.

const
    string = 'path1.path2.path3',
    result = [];

let p = string.indexOf('.');

while (p !== -1) {
    result.push(string.slice(0, p));
    p = string.indexOf('.', p + 1);
}

result.push(string);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392