Comprehensive route from a one-dimensional array

I have a specific array structure that looks like this :

var items = [
[1, 0, 'Apple'],
[2, 1, 'Banana'],
[3, 0, 'Orange'],
[4, 3, 'Grape'],
[5, 0, 'Cherry'],
[6, 0, 'Mango'],
[7, 6, 'Pear'],
[8, 6, 'Coconut'],
[9, 8, 'Pineapple'],
[10, 9, 'Watermelon']];

The desired output format should be as follows:

\Apple
\Apple\Banana
\Orange
\Orange\Grape etc...

I'm attempting to modify the functionality of a PHP function like so:

function display_items($parent, $level, $array) {
    $display = "";
    foreach ($array as $item) {
        if ($parent === $item['parentid']) {
       for ($i = 0; $i < $level; $i++) {
            $display .= "-";
       }
       $display .= " " . $item['name'] . "<br />";
       $display .= display_items($item['id'], ($item + 1), $array);
    }
}
return $display;

}

The goal is to replace the "-" with the full path of the items.

Answer №1

To create a structured object containing identifiers and their related children, you can establish paths for these relations.

function generatePaths(relations) {
    const
        iterate = path => ([id, value]) => {
            var p = path.concat(value);            
            result.push(p.join('\\'));
            (relations[id] || []).forEach(iterate(p));
        },
        result = [];
    relations[0].forEach(iterate(['']));
    return result;
}

var folders = [[1, 0, 'SAV'], [2, 1, 'OLD'], [3, 0, 'Working doc'], [4, 3, 'User'], [5, 0, 'Documentation'], [6, 0, 'Specification'], [7, 6, 'Components'], [8, 6, 'test'], [9, 8, 'subtest'], [10, 9, 'subsubtest']],
    relations = folders.reduce((r, [id, parent, value]) => {
        r[parent] = r[parent] || [];
        r[parent].push([id, value]);
        return r;
    }, Object.create(null));

console.log(generatePaths(relations));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To solve this problem, we can utilize the .map(), .find(), and .replace() functions in JavaScript. The code snippet below demonstrates how this can be achieved...

var folders = [
  [1, 0, 'SAV'],
  [2, 1, 'OLD'],
  [3, 0, 'Working doc'],
  [4, 3, 'User'],
  [5, 0, 'Documentation'],
  [6, 0, 'Specification'],
  [7, 6, 'Components'],
  [8, 6, 'test'],
  [9, 8, 'subtest'],
  [10, 9, 'subsubtest']
];

function sortFolders(arr) {
  return arr.map(folderArr => {
    let parentFolder = arr.find(el => el[0] === folderArr[1])
    let string = (parentFolder) ?
      `/${parentFolder[2]}/${folderArr[2]}` :
      `/${folderArr[2]}`
    return string.replace(/\\/g, '\\');
  })
}

sortFolders(folders); // The resulting array contains the desired folder structure...
// [
//  '/SAV',
//  '/SAV/OLD',
//  '/Working doc',
//  '/Working doc/User',
//  '/Documentation',
//  '/Specification',
//  '/Specification/Components',
//  '/Specification/test',
//  '/test/subtest',
//  '/subtest/subsubtest'
// ]

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

Tips for maintaining authentication in a Next.js application with Firebase even when tokens expire or the page is refreshed

Struggling with firebase authentication flows while building an app using firebase and next.js. Everything was going smoothly until I encountered a bug or error. When my computer remains logged in to the app for some time and I refresh the page, it redirec ...

Upon reloading, Nextjs static build automatically redirects users to the homepage

After creating a static Next.js build using npm run export, I encountered an issue while deploying the build on S3 or any other web server such as Apache with .htaccess or Nginx. When accessing the routes by pasting them directly into the browser, they wou ...

What is the best method for styling arrays displayed by React in version 15 using CSS?

React v15 has made a change where elements of arrays in JSX are now rendered as <!--react-text:some_id-->text<!--/react-text--> instead of spans. I've searched for a solution but haven't been able to figure out how to apply CSS styles ...

Employing jQuery, how can one assign attributes to appended HTML and store them

So, I am currently working on a backend page for managing a blog. This page allows users to create, edit, and delete articles. When the user clicks the "edit" button for a specific article named 'foo', the following actions are performed: The ...

"An error occurred: Uncaught SyntaxError - The import statement can only be used within a module. Including a TypeScript file into a

I need to integrate an Angular 10 TypeScript service into a jQuery file, but I am facing an issue. When I try to import the TypeScript service file into my jQuery file, I encounter the following error: Uncaught SyntaxError: Cannot use import statement outs ...

What is the best way to save a series of values into separate arrays and then combine them together in VBA?

I am fairly new to VBA and struggling to effectively manipulate range and array values. Currently, I am working on a user form where I need to merge the values from two user-provided ranges into a single array for sorting purposes, followed by using them ...

Automatically updating a database value in CodeIgniter after a countdown has expired

I am looking to automatically update a value in my MySQL database using CodeIgniter once a countdown timer reaches zero. However, I am struggling to figure out how to implement this. Here is an example: I have a database structured like this: [image lin ...

Pressing the submit button will not successfully forward the form

I've encountered an issue with my submit buttons - when I click on them, nothing happens. They were functioning properly before, but now they seem to be unresponsive. What could be causing this problem? <form id="contact" name="updateorder" acti ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Removing an element in Vue.js

Can someone help me with a Vue.js issue I'm having? I'm working on a quiz and I want to add a button that deletes a question when clicked. Here's what I've tried so far: deleteQuestion(index) { this.questions.splice(index, ...

Can you identify any issues with this Javascript code's "If" condition?

In my JavaScript code, I have an "if condition" that looks like this: for (var i in data) { //Gender.push("Gender " + data[i].JenisKelaminID); if (data[i].JenisKelaminID == 1) { Gender.push("Men"); } if (data[i].JenisKelaminID == 2) { Gend ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

Troubleshooting: jQuery.load function not functioning properly within ASP.NET MVC

I'm facing an issue with my code setup. Currently, I have the following components in different files: @Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html"))) This is included in my Razor file. <li><a href="#">Personal Re ...

In the context of NextJs, the req.body is treated as an object within the middleware, but transforms

Here is the middleware function responsible for handling the origin and CORS: export async function middleware(request: NextRequest) { const requestHeaders = new Headers(request.headers) const origin = requestHeaders.get('origin') ?? '& ...

Tips for sending a PHP JSON array to a JavaScript function using the onclick event

I am trying to pass a PHP JSON array into a JavaScript function when an onclick event occurs. Here is the structure of the PHP array before being encoded as JSON: Array ( [group_id] => 307378872724184 [cir_id] => 221 ) After encoding the a ...

Creating an HTML table with collapsed borders and hidden rows/columns using the `border-collapse

I am facing a situation where I have a table with multiple lines as shown below: <table> <tr id="line1"><td>Line</td><td>1</td></tr> <tr id="line2"><td>Line</td><td>2</td></t ...

Generating a new date instance using a specified date string and locale settings

After scouring SO and coming up empty, I'm forging ahead with my question: I've got a date string that's dependent on locale, along with the locale info itself. For example, dateStr = '06/07/2021' and locale='en-GB'. H ...

Transferring information between a pair of input fields using ngModel

There are two input fields named input1 and input2. An event has been created where anything typed in input1 is displayed in input2. However, if something is manually changed or typed into input2, the event should not trigger. I think I may need to use a ...

Applying a value to all JSON objects within an array using AngularJS and JavaScript

Tale: I've developed an array ($scope.mainArray) that will be displayed in a <table> with <tr> elements using ng-repeat as shown below: +---+ | 1 | +---+ | 2 | +---+ | 3 | +---+ Each object contains an array which is presented within & ...

Randomly undefined custom jQuery function

Appreciate your assistance in advance. I am facing a peculiar scope issue on a page where multiple charts are rendered intermittently. I have created a set of jQuery functions to display different types of charts based on the provided options. Each funct ...