简体   繁体   中英

Underscore recursive groupBy array of string arrays

I'm trying to combine and group an array with a bunch of flat arrays that contain only strings, no objects.

So my array looks something like this:

var array = [
    ["MotherNode", "Node1", "ChildNode1", "ChildOfChildNode1"],
    ["MotherNode", "Node1", "ChildNode2", "ChildOfChildNode2"],
    ["MotherNode", "Node2", "ChildNode3", "ChildOfChildNode3"],
    ["MotherNode", "Node2", "ChildNode3", "ChildOfChildNode4"],
    ["MotherNode", "Node3", "ChildNode4", "ChildOfChildNode5"],
    ["MotherNode", "Node3", "ChildNode4", "ChildOfChildNode5"]
]

Im doing this in javascript/angularjs and so far I've gathered that the best solution is probably to use underscore.js groupBy/combine methods. However most of the examples that i can find are dealing with arrays of objects where they can group them together by using a value's key. And I'm not good enough with algorithms yet to be able to figure this out on my own.

The array I'm dealing with can have hundreds of values and the result array could get 5-10 levels deep.

The result I'd like by parsing the above array would look something like this:

var result= {
    "MotherNode": [{
        "Node1":[{
            "ChildNode1":"ChildOfChildNode1"
            },{
            "ChildNode2":"ChildOfChildNode2"
        },{
        "Node2":[{
            "ChildNode3":["ChildOfChildNode3","ChildOfChildNode4"]
        },{
        "Node3":[{
            "ChildNode4":"ChildOfChildNode5"
        }
    ]
}

So does anyone have any clue how this can be done? I'm completely out of ideas.

I solved this using _.reduce grouping wasnt the way to go

   var result = _.reduce(array,function(memo, val){ 
        var tmp = memo;
            _.each(val, function(fldr){
                if(!_.has(tmp, fldr)){
                    tmp[fldr] = {}
                }
                tmp = tmp[fldr]
            })

        return memo
    },{})

the end leaf wont be set as a value but it should be easy to change that behavior to whatever suits you use case

{ MotherNode: 
   { Node1: 
      { ChildNode1: { ChildOfChildNode1: {} },
        ChildNode2: { ChildOfChildNode2: {} } },
     Node2: { ChildNode3: { ChildOfChildNode3: {}, ChildOfChildNode4: {} } },
     Node3: { ChildNode4: { ChildOfChildNode5: {} } } } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM