2015-07-22 60 views
0

我有一个应用程序,其中的对象用于显示用户系统上文件的树视图。它的结构是这样的:在递归函数中保留对象引用

[{ 
    text: 'C:/', 
    type: 'dir', 
    nodes: [ 
     { 
     text: 'foo', 
     type: 'dir', 
     nodes: [] // And so on 
     }, 
     { 
     text: 'bar', 
     type: 'file' 
     } 
}] 

按照约定,我想要先显示目录,然后再显示文件。不幸的是,无论项目类型如何,我的数据都按字母顺序检索。

为了解决这个问题我写了一个漂亮的递归函数

var sort = function (subtree) 
{ 
    subtree = _.sortBy(subtree, function (item) 
    { 
     if (item.nodes) 
     { 
     sort(item.nodes) 
     } 
     return item.type 
    }); 
} 

var tree = someTreeData; 
sort(tree); 

我使用lodash字母顺序按文件类型排序每个nodes阵列。不幸的是,子树似乎并没有引用树对象,因为当我登录其输出时,它仍然未排序。我该如何补救?

回答

2

您可以使用JavaScript内置的Array.prototype.sort函数进行排序。它接受两个参数并进行比较。请注意,排序item.notes里面的sortBy键提取器是不合适的。

function isDirectory(node) { 
    return !!node.nodes; 
} 

function sortTree(subtree) { 
    subtree.sort(function (a, b) { 
     return a.type < b.type ? -1 : 
       a.type > b.type ? 1 : 0; 
    }); 

    subtree 
     .filter(isDirectory) 
     .forEach(function (node) { 
      sortTree(node.nodes); 
     }); 
} 
+0

工作完美,只需稍作修改''.forEach(function(node){sortTree(node.nodes)});''' – Harangue