const shortenPath = str => {
const paths = str.split('/');
let stack = [];
 
for (const path of paths) {
if (!path || path === '.') {
continue;
}
 
if (path === '..') {
if (!!stack.length) {
stack.pop();
}
} else {
stack.push(path);
}
}
 
return stack;
};
 
console.log(shortenPath('/foo/../test/../test/../foo//bar/./baz'));
// '/foo/bar/baz'
 
Click Run to execute JavaScript.
Code runs in an isolated environment.