递归地对树进行排序

时间:2016-09-06 14:05:59

标签: javascript algorithm sorting tree

我想为对象树中的每个根对子进行排序 - 我该怎么做?

树:

{
 folder: { id: 1, name: 'root' },
 children: [
  {
   folder: { id: 2, parentId: 1, name: 'zzz' },
   children: []
  },
  {
   element: { id: 1, name: 'aaa' },
   children: []
  }
 ]
}

对它进行排序会在这里交换文件夹和元素等。实际的树要大得多,深度要高得多。我怎么能这样做?

我有一个算法在这棵树中找到了一些东西:

/**
 * searchFor {
 *   type: '',
 *   index: '',
 *   value: ''
 * }
 */
var search = function (data, searchFor) {
    if (data[searchFor.type] != undefined &&
        data[searchFor.type][searchFor.index] == searchFor.value) {
        return data;
    } else if (data.children != null) {
        var result = null;
        for (var i = 0; result == null && i < data.children.length; i++) {
            result = search(data.children[i], searchFor);
        }
        return result;
    }
    return null;
};

但老实说,我不知道如何才能对它进行排序。我该怎么做?

我尝试了类似的东西,但它不起作用:

/**
 * sortBy {
 *   type: '',
 *   index: '',
 *   order: '' // asc/desc
 * }
 */
var sort = function (data, sortBy) {
    if (data.children != null) {
        // sort all children here, but how?

        var result = null;
        for (var i = 0; result == null && i < data.children.length; i++) {
            result = search(data.children[i], sortBy);
        }
        return result;
    }
    return null;
}

1 个答案:

答案 0 :(得分:0)

这应该有效。

function sortTree(tree){
    tree.children.sort(function(a,b){
        if (a.folder !== undefined && b.folder === undefined) return -1;
        if (a.folder === undefined && b.folder !== undefined) return 1;
        a = a.folder === undefined ? a.element;
        b = b.folder === undefined ? b.element;
        if (a.name == b.name) return 0;
        return a.name < b.name ? -1 : 1;
    });
    for (i = 0; i < tree.children.length){
        sortTree(tree.children[i])
    }
}