String arrays grouped recursively by underscore in an array structure

I'm facing a challenge where I need to combine and group an array consisting of multiple flat arrays containing only strings, without any objects.

Here's how my array looks like:

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", "ChildOfChildNode6"]
]

I am working on this task in javascript/angularjs and I believe that utilizing underscore.js' groupBy/combine methods might be the most effective approach. However, existing examples mostly focus on array grouping based on key values within objects, which is slightly different from my scenario. As I am still learning about algorithms, finding a solution on my own seems challenging at this point.

The array I have can potentially contain hundreds of entries, leading to a nested result array with 5-10 levels depth.

If we were to transform the above array, here is the desired outcome:

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

If anyone has insights on how to achieve this task, I would greatly appreciate the guidance as I currently feel stuck with no clear direction.

Answer №1

I managed to solve this utilizing the _.reduce method instead of grouping

   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 final leaf won't be designated as a value, but it can easily be customized to suit your specific use case

{ MasterNode: 
   { Node1: 
      { ChildNode1: { GrandchildNode1: {} },
        ChildNode2: { GrandchildNode2: {} } },
     Node2: { ChildNode3: { GrandchildNode3: {}, GrandchildNode4: {} } },
     Node3: { ChildNode4: { GrandchildNode5: {} } } } }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding an image as a header in Angular UI Grid: A step-by-step guide

I want to include an image in the header instead of within the rows. var app = angular.module('app', ['ngAnimate', 'ngTouch', 'ui.grid']); app.controller('MainCtrl', ['$scope', '$http' ...

Ways to retrieve the chosen option in a dropdown list without specifying the dropdown's name, id,

Custom dropdown, Model-View-Controller Code @foreach (var attribute in Model) { string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id); @switch (attribute.AttributeControl ...

Using Nested Maps in React to Fetch JSON Data

As someone who is relatively new to javascript and react, I've been honing my skills by practicing various techniques. Currently, I'm trying to work with JSON data to render multiple HTML blocks in a format resembling a basic schedule. Initially, ...

Ways to ensure the first div always expands when sorting in AngularJS

In my AngularJS application, I have a set of div elements generated using ng-repeat. The first div is always expanded by default upon loading the page. Now, when I click a button to sort the divs based on their ID in the JSON data, I want the top div to ...

What is the process for retrieving the page name and authToken from a URL using an Express GET route in Node.js?

I have a URL structured like this: http://localhost:3000/pageName and I am defining my express route as follows: app.get("/:pageName",(req,res)=>{ if (authentication === true) { res.render(req.param.pageName) } }) The above code works correctly when ...

Reorganize information within an array containing nested arrays using associative keys

I'm in need of assistance with a specific issue and hoping to find guidance here. Could anyone tell me if there is a built-in PHP function to restructure the array I receive from an HTML form? Current Array $array = [ 'product_template_id&ap ...

Send the form validation result to PHP

Currently, I am working on a basic form that includes a script to validate the data before submission: <form action='self.php' name='my_form' method='post' onSubmit="return checkit();"> <select name='menu&ap ...

Is the popup not opening with just one click?

https://i.stack.imgur.com/09dcf.png Upon clicking the first input cell, the popup opens and closes as expected. However, when closing the initial input and opening another one, an orange mark icon appears but the popup doesn't open until the second c ...

Dynamic conversion of values between the view and scope

I am looking to automatically translate the language of each menu title based on the user's session within their profile. To accomplish this, I plan to leverage our API Library within our php framework. In traditional php usage, we typically translat ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Angular input field displaying X

Hey everyone, I'm currently working with Angular and typescript. I have a requirement to hide the first 8 characters that the user enters and only show the remaining 4 characters. Update: I have included a link to the Stackblitz demo Stackblitz <i ...

Combine two values that have been added to two different jQuery objects

I am struggling with a coding issue that involves combining two different values, one in miles and the other in km, into a single column separated by '/'. Can anyone provide guidance on how to achieve this? @$el.append @odometerColumn2.render(). ...

Transform a string array, where each string contains values separated by dots, into a multidimensional array

Here is a sample array that needs to be converted into a multidimensional array: Array ( [0] => INBOX.Trash [1] => INBOX.Sent [2] => INBOX.Drafts [3] => INBOX.Test.sub folder [4] => INBOX.Test.sub folder.test 2 ) Is the ...

Unable to navigate to the frame within the Salesforce Lightning interface

Attached below is the screenshot and code that I have used: driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@title,'Deploy Data Set')]"))); <div class="slds-template_iframe slds-card" force-aloha-page_aloha-page=""> ...

What is the right rendering strategy to use for shouldComponentUpdate in React?

Provide an exhaustive list of all props required for rendering shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; ...

Storing data in JSON format and retrieving it using Javascript

My challenge involves plotting a chart using values from an object's list in my view with High Chart. However, I face the issue of accessing my model from JavaScript. public class MortgageCalculator { public List<double> interest_month = new ...

divide a lengthy string into several dynamic divisions

I am attempting to divide a lengthy string into multiple dynamic divs once the height of the div reaches a certain limit. Below is the code that I believed would achieve this: $(document).ready(function () { var arr = longishstring.split(' ' ...

Enhance the appearance of the <td> <span> element by incorporating a transition effect when modifying the text

I need help with creating a transition effect for a span element within a table cell. Currently, when a user clicks on the text, it changes from truncated to full size abruptly. I want to achieve a smooth growing/scaling effect instead. You can view an exa ...

Steps for inserting levels into nested objects:

I am working on dynamically adding levels to a nested object structure. Here is an example: [{ "_id": "5a8855df9a8bb60e749c9d87", "name": "Test3", "children": [] }, { "_id": "5a8856569a8bb60e749c9d88", "name": "Test4", "childre ...

An ajax call triggers a 500 error response when initiated within another ajax call

I am encountering an issue with my Ajax requests. There are two requests - one (referred to as Ajax#1) sends data to the backend, and the other (Ajax#2) uses that data to load content onto the front end. To ensure that Ajax#2 runs after Ajax#1, I attempt ...