Ways to organize a directory structure of folders

I am working with a tree structure of folders that have properties such as id, parent_id, and name. Currently, this tree is stored in an unsorted array.

Each element in my array looks like this:

var obj = { id: 1, parent_id: null, name: "Folder" }

My goal is to sort this array in order to display the folder hierarchy in a structured manner, like:

Folder1
  Sub_folder1
    Sub_sub_folder1
  Sub_folder2
    Sub_sub_folder2

And so on... I am trying to achieve this without using recursion but I am facing challenges in doing it effectively.

Below are some attempts I have made. One approach involved adding an artificial field representing the number of each folder in the collection, however, this method did not produce the desired outcome:

var sort = function(list) {

  var f_map = {};
  var sorting_index = 1;
  var tree = angular.copy(list);

  for(var i = 0; i < tree.length; i++) {

    var node = tree[i];
    f_map[ node.id ]= { index: i, children: [] };

    if (node.parent_id) {
      f_map[ node.parent_id ].children.push( node.id );
    };

    var idx = 0;
    var visited = {};

    for(var key in f_map) {
      var index = f_map[key].index;
      var node = tree[index];
      if (!visited[node.id]) {
        node.nuid = idx++;
      } else {
        visited[node.id] = true;
      };
      if (f_map[key].children.length) {
        var children = f_map[key].children;
        for(var i = 0; i < children.length; i++) {
          var child_id = children[i];
          var child_idx = f_map[child_id].index;
          var child = tree[child_idx];
          child.nuid = idx++;
          visited[child.id] = true;
        };
      };
    };

    tree.sort(function(left, right) {
      return left.nuid - right.nuid;
    });

    return tree;
};

Answer β„–1

When representing the parent pointer as a reference to the id of the parent node, it is suggested to alter the way folders are represented into an object form:

var folders = {
    1: {parent_id: null, name: "Folder", path: null},
    ...
};

A path field has been included to allow for the memoization of the results from this recursive function used to determine the full path of a folder:

function path(node) {
    if (node.path !== null) return node.path;
    if (node.parent_id === null) {
        node.path = '/' + node.name;
    } else {
        node.path = path(folders[node.parent_id]) + '/' + node.name;
    }
    return node.path;
}

To perform a Schwartzian transform, start by extracting the sorting field along with a reference to the item:

var keys = [];

Object.keys(folders).map(function (key) {
    var folder = folders[key];
    keys.push({path: path(folder), id: key});
});

The next step involves sorting the keys array:

keys.sort(function (a, b) {
    var apath = a.path;
    var bpath = b.path;

    // To compare folder paths effectively
    return apath.localeCompare(bpath);
});

Lastly, generate the folders in sorted order by iterating through the keys array:

var sorted_folders = keys.map(function (item) {
    return folders[item.id];  
});

The resulting sorted_folders will be a collection of folder objects, with the option to extract specific properties as needed during this process.

Answer β„–2

Let's start by clarifying that recursion is far from being slow - in fact, it's a powerful tool to have at your disposal. It simplifies the process of solving specific problems.

Below is an algorithm designed to tackle this particular issue:

1. In cases where the graph can be considered a forest rather than a tree:
       - Create a new node as the root
       - Ensure all roots in the forest point to this newly created root as their parent
2. For each node, establish an array (stack) consisting of its children, denoted as c[i].
3. For every vertex v in the tree:
       - Add v to c[v.parent]
4. Set u as the root and initialize i to 0
5. Output u
6. While c[root] is not empty and u is not equal to the root:
       - If c[u] is not empty:
           - Pop the top element from c[u], assign it to u
           - Increment i by 1
           - Print tab i times
           - Output u
       - If c[u] is empty and u is not the root:
           - Set u to u.parent
           - Decrement i by 1

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

Determine the dimensions of the objects within a JSON array

My JSON response creation looks like this : { "G5LDUHRPEEA6B-39CFBWYA": [], "JMSK0DKOEEA0UXMY750O3W": [], "ISVN8JF1EEAD3W398ZNOSA": [ { "delloData": "1478644629", "ref": "75", "dataType": "String", "somePart": LA, ...

Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values. Checkboxes: <input type='checkbox' name='foo1' value='foo1' v-model="sele ...

Is there a comparable syntax in F# to C#'s "unsafe" block?

Checking array boundaries can significantly decrease speed, especially with 2D arrays. Is there a method to incorporate unsafe code blocks in F# for improved performance? ...

Tips for effectively splitting arrays nested within an array using JavaScript

Here is an example of slicing an array to generate a new one: var array= [ [1,"dataA","dataB","dataC","dataD"...], [2,"dataA","dataB","dataC","dataD"...], [3,"dataA","dataB","dataC","dataD"...], [4,"dataA","dataB","dataC","dataD"...]... ...

Unable to locate the variable named setState

Having trouble creating a toggle button that changes icon and color when clicked? I'm following a tutorial but encountered an issue. Despite attempting different modifications, the same error persists: "Cannot Find Variable: setState" Variable Error ...

Issue: When using Android Kotlin to add an item to an Array<JSONObject> or JSONArray, it is causing an Array

Currently, I am encountering an issue where I need to convert a mutable list into a JSON array in order to send it to the next activity. It seems impossible to directly pass the mutable list without including any serialization plugin. This is the code sni ...

Tips for efficiently combining mergeMap observables and providing a singular value for the entire observable

Consider this particular case involving TypeScript/angular with rxjs 6.5: main(){ const items = ['session', 'user']; const source: Observable<any> = from(items); source .pipe( ...

Looking to determine if a specific element is assigned multiple class names

Help needed! Can you tell me how to check if an element contains more than one classname using pure javascript, without using jQuery? For example: If #test has both the classnames "classA and classB", then { alert(true) } else { alert(false) } Here is ...

The POST request is not functioning. An error has occurred: Unable to retrieve response data - no content is available for the preflight request

Having trouble making a post request from my client side to the back-end. Even with the new movie hardcoded, it keeps returning an error stating that there was a failure in loading the response data. Below is the code for the front-end: //Fetch request t ...

Incorporating and utilizing the HTML5-captured image as a point of reference

I understand that all I need to do to achieve this is insert <input type="file" id="photo" accept="image/*;capture=camera"> However, my lack of coding skills has caused issues with actually grabbing and using the image selected/taken by the user. ...

Is there a way to link a knockout observable to the jquery barrating plugin?

I have integrated the jquery bar-rating plugin with a knockout viewModel. Currently, all ratings need to be manually selected, but I am looking to convert the variable (let's call it rating) into an observable so that the bar automatically updates whe ...

What are the steps for modifying JSON Arrays?

Looking for a way to streamline my JSON array by removing unwanted keys and simplifying the structure. Any recommendations on software or websites that can help with this task? Basically, I want to transform data like this: "δΈ€": { "st ...

Determine if a specific string is present in any of the values within an array by utilizing

A scenario: I have a cookie that has been split into an array: var treats = document.cookie.split(';'); [dogs=bla, cats=sdfgh, cabbages=kjhgfdfg] If I aim to locate the index of 'cats=sdfgh', I can utilize treats.indexOf('cats= ...

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

Implementing conditional visibility toggling in React

I am experiencing an issue where I am attempting to change a div's visibility from hidden to visible upon button click. Despite clicking the button, the visibility of the div does not change as expected. Upon inspecting the console after executing the ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Creating a 2D array filled with strings

I am facing some difficulties with a practice homework assignment that is not being graded. This task requires me to develop a function named find_name with two parameters. The first parameter is a 2D array containing names (strings), while the second par ...

Implementing a method to pass on an incrementing index condition from one component to another using provide and inject in Vue.js

I attempted to enhance the tabsWrapper component by adding a button that, when clicked, selects the next tab. However, my code isn't functioning as expected despite using familiar patterns. My lack of understanding regarding slots, inject, and provide ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...

Getting values from a JSON array in Swift 4 - a step-by-step guide

I have the following code snippet written in Swift 4 using Alamofire: Alamofire.request("http://xxxx.pl/id=1", method: .get, parameters: nil) .responseJSON { response in let jsonResponse = JSON(response.result.value!) let resData = jsonRespon ...