Divide a path in multiple full paths in JavaScript

I try to find the best way to have an array of ‘full’ paths from one path.

Input :

'source/folder/folder2/folder3/file'

I would like to have this output:

[
'/',
'/folder',
'/folder/folder2',
'/folder/folder2/folder3',
'/folder/folder2/folder3/file'
]

Currently, I can see that my code is not optimized:

 pathArray = path.split('/');
 if (pathArray [0] === '') {
   pathArray .shift();
 }
 if (pathArray [pathArray .length - 1] === '') {
    pathArray .pop();
 }
 const finalArrayPath = [];
 for (let i = 0; i < pathArray.length; i++) {
   let path = '';
   for (let j = 0; j <= i; j++) {
     path = path + pathArray[j] + '/';
   }
   finalArrayPath.push(path);
 }

More of that, my code have a / at the end of each paths and source at the beginning, I could add code for removing these but I would like a more optimized code.

Answer

Using Array.prototype.reduce method you could do:

const path = "source/folder/folder2/folder3/file";

const result = path.split("/").slice(1).reduce((allPaths, subPath) => {
  const lastPath = allPaths[allPaths.length-1];
  allPaths.push(lastPath.endsWith("/") ? (lastPath + subPath) : `${lastPath}/${subPath}`);
  return allPaths;
}, ["/"]);

console.log(result)