Turning a 2D array into a tree The 2019 Stack Overflow Developer Survey Results Are In ...

Typeface like Times New Roman but with "tied" percent sign

What was the last x86 CPU that did not have the x87 floating-point unit built in?

What is special about square numbers here?

Simulation of a banking system with an Account class in C++

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

Is it ethical to upload a automatically generated paper to a non peer-reviewed site as part of a larger research?

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

ELI5: Why do they say that Israel would have been the fourth country to land a spacecraft on the Moon and why do they call it low cost?

Did the new image of black hole confirm the general theory of relativity?

Can a novice safely splice in wire to lengthen 5V charging cable?

How do I add random spotting to the same face in cycles?

How can I protect witches in combat who wear limited clothing?

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

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

What aspect of planet Earth must be changed to prevent the industrial revolution?

How did the audience guess the pentatonic scale in Bobby McFerrin's presentation?

Why can't wing-mounted spoilers be used to steepen approaches?

Python - Fishing Simulator

Sort a list of pairs representing an acyclic, partial automorphism

system() function string length limit

Was credit for the black hole image misattributed?

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

In horse breeding, what is the female equivalent of putting a horse out "to stud"?

I could not break this equation. Please help me



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[0]) return tree;
tree[item[0]] = tree[item[0]] || {};
if (!item[1]) return tree;
tree[item[0]][item[1]] = tree[item[0]][item[1]] || [];
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 25 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[0]) return tree;
    tree[item[0]] = tree[item[0]] || {};
    if (!item[1]) return tree;
    tree[item[0]][item[1]] = tree[item[0]][item[1]] || [];
    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 25 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[0]) return tree;
      tree[item[0]] = tree[item[0]] || {};
      if (!item[1]) return tree;
      tree[item[0]][item[1]] = tree[item[0]][item[1]] || [];
      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[0]) return tree;
      tree[item[0]] = tree[item[0]] || {};
      if (!item[1]) return tree;
      tree[item[0]][item[1]] = tree[item[0]][item[1]] || [];
      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 25 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 25 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

                    is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

                    How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

                    Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...