平面阵列的完整路径

时间:2018-11-22 20:53:35

标签: javascript arrays path tree

我有一个像这样的数组:

console.log([1,2,3,4,5].reduce((a,b) => a + b, 0))

// throws a TypeError...
console.log([].reduce((a,b) => a + b))

输出应为

var folders = [
[1, 0, 'SAV'],
[2, 1, 'OLD'],
[3, 0, 'Working doc'],
[4, 3, 'User'],
[5, 0, 'Documentation'],
[6, 0, 'Specification'],
[7, 6, 'Components'],
[8, 6, 'test'],
[9, 8, 'subtest'],
[10, 9, 'subsubtest']];

我尝试修改此php函数

\SAV
\SAV\OLD
\Working doc
\Working doc\User ect...

}

目的是用完整路径替换“-”

2 个答案:

答案 0 :(得分:0)

您可以构建一个具有标识符及其子关系的对象,然后创建关系的路径。

function getPathes(relations) {
    const
        iter = path => ([id, value]) => {
            var p = path.concat(value);            
            result.push(p.join('\\'));
            (relations[id] || []).forEach(iter(p));
        },
        result = [];
    relations[0].forEach(iter(['']));
    return result;
}

var folders = [[1, 0, 'SAV'], [2, 1, 'OLD'], [3, 0, 'Working doc'], [4, 3, 'User'], [5, 0, 'Documentation'], [6, 0, 'Specification'], [7, 6, 'Components'], [8, 6, 'test'], [9, 8, 'subtest'], [10, 9, 'subsubtest']],
    relations = folders.reduce((r, [id, parent, value]) => {
        r[parent] = r[parent] || [];
        r[parent].push([id, value]);
        return r;
    }, Object.create(null));

console.log(getPathes(relations));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

我们可以使用 .map() .find() .replace()方法来实现,请参见JavaScript中的解决方案下面...

var folders = [
  [1, 0, 'SAV'],
  [2, 1, 'OLD'],
  [3, 0, 'Working doc'],
  [4, 3, 'User'],
  [5, 0, 'Documentation'],
  [6, 0, 'Specification'],
  [7, 6, 'Components'],
  [8, 6, 'test'],
  [9, 8, 'subtest'],
  [10, 9, 'subsubtest']
];

function sortFolders(arr) {
  return arr.map(folderArr => {
    let parentFolder = arr.find(el => el[0] === folderArr[1])
    let string = (parentFolder) ?
      `/${parentFolder[2]}/${folderArr[2]}` :
      `/${folderArr[2]}`
    return string.replace(/\\/g, '\\');
  })
}

sortFolders(folders); // Returns an array with the expected output...
// [
//  '/SAV',
//  '/SAV/OLD',
//  '/Working doc',
//  '/Working doc/User',
//  '/Documentation',
//  '/Specification',
//  '/Specification/Components',
//  '/Specification/test',
//  '/test/subtest',
//  '/subtest/subsubtest'
// ]