Turning a 2D array into a tree The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Javascript widget patterns and merging configurationsTurning multiple PHP arrays into one array ready for conversion to JavascriptRendering JSON array as a treeGrowing my own Tree (Structure)Array implementation of unbalanced binary search treeCreate a Tree Node from JavaScript ArrayPromises turning into pyramidsMake binary search tree from sorted arrayCoding Decision Trees in VBAGeneric binary search tree in C++

What is special about square numbers here?

How can I define good in a religion that claims no moral authority?

Make it rain characters

Can withdrawing asylum be illegal?

Searching for a differential characteristic (differential cryptanalysis)

What do you call a plan that's an alternative plan in case your initial plan fails?

What are these Gizmos at Izaña Atmospheric Research Center in Spain?

He got a vote 80% that of Emmanuel Macron’s

Am I ethically obligated to go into work on an off day if the reason is sudden?

First use of “packing” as in carrying a gun

I could not break this equation. Please help me

How are presidential pardons supposed to be used?

Did the UK government pay "millions and millions of dollars" to try to snag Julian Assange?

Does Parliament need to approve the new Brexit delay to 31 October 2019?

Can smartphones with the same camera sensor have different image quality?

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

What information about me do stores get via my credit card?

Was credit for the black hole image misattributed?

Keeping a retro style to sci-fi spaceships?

The variadic template constructor of my class cannot modify my class members, why is that so?

Sort a list of pairs representing an acyclic, partial automorphism

Road tyres vs "Street" tyres for charity ride on MTB Tandem

system() function string length limit

How do you keep chess fun when your opponent constantly beats you?



Turning a 2D array into a tree



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Javascript widget patterns and merging configurationsTurning multiple PHP arrays into one array ready for conversion to JavascriptRendering JSON array as a treeGrowing my own Tree (Structure)Array implementation of unbalanced binary search treeCreate a Tree Node from JavaScript ArrayPromises turning into pyramidsMake binary search tree from sorted arrayCoding Decision Trees in VBAGeneric binary search tree in C++



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


I have the following data structure that's obtained from a third party:



var data = [
["Parent1", "Parent1.1", "Parent1.1.1"],
["Parent2", "Parent2.1", "Parent2.1.1"],
["Parent3", "Parent3.1", "Parent3.1.1"],
["Parent1", "Parent1.2", "Parent1.2.1"],
["Parent1", "Parent1.2", "Parent1.2.2"]
];


Where child nodes may or may not be present.

I'm turning it into a tree to represent the data logically:



var tree = 
"Parent1":
"Parent1.1": ["Parent1.1.1"],
"Parent1.2": ["Parent1.2.1", "Parent1.2.2"]
,
"Parent2":
"Parent2.1": ["Parent2.1.1"]
,
"Parent3":
"Parent3.1": ["Parent3.1.1"]

;


What I'm currently doing seems rather straightforward to myself, but somewhat convoluted due to the numerous return statements:



var tree = data.reduce(function(tree, item) [];
if (!item[2]) return tree;
tree[item[0]][item[1]].push(item[2]);
return tree;
, ); //Returns as shown above


Is there a better way to approach this problem, what improvements could be made?

The depth of the data is always fixed at three.










share|improve this question









$endgroup$




bumped to the homepage by Community 11 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.





















    4












    $begingroup$


    I have the following data structure that's obtained from a third party:



    var data = [
    ["Parent1", "Parent1.1", "Parent1.1.1"],
    ["Parent2", "Parent2.1", "Parent2.1.1"],
    ["Parent3", "Parent3.1", "Parent3.1.1"],
    ["Parent1", "Parent1.2", "Parent1.2.1"],
    ["Parent1", "Parent1.2", "Parent1.2.2"]
    ];


    Where child nodes may or may not be present.

    I'm turning it into a tree to represent the data logically:



    var tree = 
    "Parent1":
    "Parent1.1": ["Parent1.1.1"],
    "Parent1.2": ["Parent1.2.1", "Parent1.2.2"]
    ,
    "Parent2":
    "Parent2.1": ["Parent2.1.1"]
    ,
    "Parent3":
    "Parent3.1": ["Parent3.1.1"]

    ;


    What I'm currently doing seems rather straightforward to myself, but somewhat convoluted due to the numerous return statements:



    var tree = data.reduce(function(tree, item) [];
    if (!item[2]) return tree;
    tree[item[0]][item[1]].push(item[2]);
    return tree;
    , ); //Returns as shown above


    Is there a better way to approach this problem, what improvements could be made?

    The depth of the data is always fixed at three.










    share|improve this question









    $endgroup$




    bumped to the homepage by Community 11 mins ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      4












      4








      4





      $begingroup$


      I have the following data structure that's obtained from a third party:



      var data = [
      ["Parent1", "Parent1.1", "Parent1.1.1"],
      ["Parent2", "Parent2.1", "Parent2.1.1"],
      ["Parent3", "Parent3.1", "Parent3.1.1"],
      ["Parent1", "Parent1.2", "Parent1.2.1"],
      ["Parent1", "Parent1.2", "Parent1.2.2"]
      ];


      Where child nodes may or may not be present.

      I'm turning it into a tree to represent the data logically:



      var tree = 
      "Parent1":
      "Parent1.1": ["Parent1.1.1"],
      "Parent1.2": ["Parent1.2.1", "Parent1.2.2"]
      ,
      "Parent2":
      "Parent2.1": ["Parent2.1.1"]
      ,
      "Parent3":
      "Parent3.1": ["Parent3.1.1"]

      ;


      What I'm currently doing seems rather straightforward to myself, but somewhat convoluted due to the numerous return statements:



      var tree = data.reduce(function(tree, item) [];
      if (!item[2]) return tree;
      tree[item[0]][item[1]].push(item[2]);
      return tree;
      , ); //Returns as shown above


      Is there a better way to approach this problem, what improvements could be made?

      The depth of the data is always fixed at three.










      share|improve this question









      $endgroup$




      I have the following data structure that's obtained from a third party:



      var data = [
      ["Parent1", "Parent1.1", "Parent1.1.1"],
      ["Parent2", "Parent2.1", "Parent2.1.1"],
      ["Parent3", "Parent3.1", "Parent3.1.1"],
      ["Parent1", "Parent1.2", "Parent1.2.1"],
      ["Parent1", "Parent1.2", "Parent1.2.2"]
      ];


      Where child nodes may or may not be present.

      I'm turning it into a tree to represent the data logically:



      var tree = 
      "Parent1":
      "Parent1.1": ["Parent1.1.1"],
      "Parent1.2": ["Parent1.2.1", "Parent1.2.2"]
      ,
      "Parent2":
      "Parent2.1": ["Parent2.1.1"]
      ,
      "Parent3":
      "Parent3.1": ["Parent3.1.1"]

      ;


      What I'm currently doing seems rather straightforward to myself, but somewhat convoluted due to the numerous return statements:



      var tree = data.reduce(function(tree, item) [];
      if (!item[2]) return tree;
      tree[item[0]][item[1]].push(item[2]);
      return tree;
      , ); //Returns as shown above


      Is there a better way to approach this problem, what improvements could be made?

      The depth of the data is always fixed at three.







      javascript array tree






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 16 '15 at 16:00









      NitNit

      3641410




      3641410





      bumped to the homepage by Community 11 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 11 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)



          var tree = data.reduce(function(tree, item) 
          var tempTree = tree;
          for(var i=0;i<item.length;i++)
          if(!tempTree[item[i]])
          tempTree[item[i]] = ;
          tempTree = tempTree[item[i]];

          return tree;
          , );





          share|improve this answer











          $endgroup$













            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f104825%2fturning-a-2d-array-into-a-tree%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0












            $begingroup$

            I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)



            var tree = data.reduce(function(tree, item) 
            var tempTree = tree;
            for(var i=0;i<item.length;i++)
            if(!tempTree[item[i]])
            tempTree[item[i]] = ;
            tempTree = tempTree[item[i]];

            return tree;
            , );





            share|improve this answer











            $endgroup$

















              0












              $begingroup$

              I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)



              var tree = data.reduce(function(tree, item) 
              var tempTree = tree;
              for(var i=0;i<item.length;i++)
              if(!tempTree[item[i]])
              tempTree[item[i]] = ;
              tempTree = tempTree[item[i]];

              return tree;
              , );





              share|improve this answer











              $endgroup$















                0












                0








                0





                $begingroup$

                I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)



                var tree = data.reduce(function(tree, item) 
                var tempTree = tree;
                for(var i=0;i<item.length;i++)
                if(!tempTree[item[i]])
                tempTree[item[i]] = ;
                tempTree = tempTree[item[i]];

                return tree;
                , );





                share|improve this answer











                $endgroup$



                I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)



                var tree = data.reduce(function(tree, item) 
                var tempTree = tree;
                for(var i=0;i<item.length;i++)
                if(!tempTree[item[i]])
                tempTree[item[i]] = ;
                tempTree = tempTree[item[i]];

                return tree;
                , );






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 18 '18 at 17:08









                Sᴀᴍ Onᴇᴌᴀ

                10.3k62168




                10.3k62168










                answered Jan 18 '18 at 16:43









                sourajitchakrabortysourajitchakraborty

                1




                1



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f104825%2fturning-a-2d-array-into-a-tree%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                    Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

                    Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar