【问题标题】:Javascript function to convert list of arrays into a tree data structure or a graph用于将数组列表转换为树数据结构或图形的 Javascript 函数
【发布时间】:2014-10-18 00:34:57
【问题描述】:

我有一个字符串数组列表:

    [FT, LW ,VN ]
    [FT ,LW ,NV ]
    [FT ,LL ,VN ]
    [FT ,LL ,NV ]
    [EM ,FT ,LW ]
    [EM ,FT ,LL ]

有人可以帮我处理这些数组并创建树或类似结构的图的 javascript 函数。 最终的输出应该是这样的:

                FT
         LW             LL
     NV,VN,EM         VN,NV,EM

我正在尝试这些功能,但似乎存在问题。我有 2 条路径来启动树。金融时报和新兴市场。

function convertToHierarchy(arry/* array of array of strings */) {
        var item, path;
        // Discard duplicates and set up parent/child relationships
        var children = {};
        var hasParent = {};
        for (var i = 0; i < arry.length; i++) {
            var path = arry[i];
            var parent = null;
            for (var j = 0; j < path.length; j++) {
                var item = path[j];
                if (!children[item]) {
                    children[item] = {};
                }
                if (parent) {
                    children[parent][item] = true; /* dummy value */
                    hasParent[item] = true;
                }
                parent = item;
            }
        }

        // Now build the hierarchy
        var result = [];
        for (item in children) {
            if (!hasParent[item]) {
                result.push(buildNodeRecursive(item, children));
            }
        }
        return result;
    }

    function buildNodeRecursive(item, children) {
        var node = {
            id : item,
            children : []
        };
        for ( var child in children[item]) {
            node.children.push(buildNodeRecursive(child, children));
        }
        return node;
    }

将不胜感激任何帮助。

【问题讨论】:

  • SO 不是免费的编码服务。您必须自己进行一些尝试,如果您在使用它时遇到问题,我们会为您提供帮助。
  • 我明白了。谢谢。我曾尝试使用递归来构建树结构,但这似乎效果不佳。
  • FT + LW + EM 是有效路径。

标签: javascript arrays data-structures jstree


【解决方案1】:

我想我可以操纵列表以根据计数的权重对它们进行排序。然后使用我提到的初始函数。谢谢你们的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2023-04-08
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多