arrange elements by their relationship with parents and children using typescript and angular

Here is a list that needs to be sorted by parent and child relationships:

0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4}

1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null}

2: {id: 5, name: "111", code: "111", type: 3, hasParent: true, parentId: 4}

3: {id: 4, name: "22", code: "22", type: 1, hasParent: false, parentId: null}

4: {id: 3, name: "yyy", code: "yyyy", type: 2, hasParent: false, parentId: null}

5: {id: 2, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: true, parentId: 1}

6: {id: 1, name: "cbcvb", code: "cvbcvcbv", type: 2, hasParent: false, parentId: null}

In order to achieve this sorting, the items with parent values equal to another item's id should be placed below that item.

The desired sorted list should look like this:

...

I attempted to write a code snippet for this sorting task, but unfortunately, it did not work as intended. The resulting list was not sorted according to the logic I described above.

Can you help me identify what went wrong in my code and suggest a solution to fix this issue?

Answer №1

In the scenario where elements are not nested, an alternative approach can be taken (although it may not yield the same outcome - there seems to be an error in assuming parentId of 3 is 6?).

this.sorted=[];
// Retrieve all elements with a parent
const childs=this.data.filter(x=>x.parentId).sort((a,b)=>a.parentId-b.parentId)

// Iterate through each child element
childs.forEach((x,i)=>{
  this.sorted.push(x)     // Add to sorted array
                          // Check if it's the last element or the next one has a different parent
  if (i==childs.length-1 || childs[i+1].parentId!=x.parentId)
     this.sorted.push(this.data.find(p=>p.id==x.parentId)) // Add the parent element

})
// Finally include elements that are not already in the list
this.data.forEach(x=>{
  if (!this.sorted.find(s=>s.id==x.id))
    this.sorted.push(x)
})

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 automating file uploads in HTML

I am having trouble filling the <input type="file"> element programmatically when trying to upload a file using a form. Can someone please provide me with guidance on how to accomplish this task? The method does not matter, I just want to achieve m ...

Waiting for a function to complete its processing loop in Angular 7

In my code, I'm dealing with an angular entity called Z which has a property that is a list of another entity named Y. My goal is to delete the entity Z, but before doing so, I need to also delete all the Y entities within it. The challenge arises fro ...

Obtain the value of a two-handle slider using jQuery

Here is the HTML and JS setup I have for implementing a jQuery two-handle range slider: .html <p> <input class="amount" readonly style="border:0; color:black; background: transparent; text-align: center;" type="text"> </p> <div cla ...

Error occurred: Unable to access 'client' property as it is undefined. Process will continue running

Hi there! I'm currently working on building a key bot for my website, but I keep encountering this error UNCAUGHT EXCEPTION - keeping process alive: TypeError: Cannot read properties of undefined (reading 'client') along with another one rel ...

Error with Typescript types when using Styled Components

After successfully setting up styled-components in react-native, I encountered an issue while trying to use it in a simple example with react-native-web: import * as React from 'react'; import styled from 'styled-components'; export d ...

Simple steps to turn off error highlighting for TypeScript code in Visual Studio Code

Hey there! I've encountered an issue with vscode where it highlights valid code in red when using the union operator '??' or optional chaining '?.'. The code still builds without errors, but vscode displays a hover error message st ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

Having four videos displayed on one webpage can cause the browser to function at a slower

I have videos that are around 30 seconds long and 15mbs. I'm wondering if it's feasible to include them on a page or if I should opt for cover images instead. I would like to use the video as a separator similar to the design showcased at Does a ...

Tips for sending variable from JavaScript to PHP Page through XMLHTTP

Make sure to review the description before flagging it as a duplicate. In my understanding, the method of transmitting data from JavaScript to PHP is through Ajax Call. This is the situation I am facing: With PHP, I bring forth an HTML page that cont ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Encountering a problem while attempting to host an Angular application on localhost:4200

After executing the ng serve command, I encountered an issue in the browser: An error occurred while trying to resolve "localhost:4200" ("") for "10.238.0.0": rpc error: code = Unknown desc = no such record I apologize if this question seems basic, as I ...

Obtain the function's return type without actually executing the function

Consider the following TypeScript function: export const foo = function(){ return { a: 1, b: true, c: 'bar' } }; If I were to import this function into another file: import {foo} from './foobar'; Is there a me ...

Error in Charts API - [draw function failed to render for one or more participants]

Currently encountering an error on the client side where one or more participants failed to draw. I am able to successfully output data in the drawVisualization call, indicating that the issue lies within the JavaScript code. Despite following examples, I ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Is there a way to simulate a click event within a Jasmine unit test specifically for an Angular Directive?

During the implementation of my directive's link function: $document.on('click.sortColumnList', function () { viewToggleController.closeSortColumnList(); scope.$apply(); }); While creating my unit test using Jasmine: describe(&apo ...

How can Angular be used for live search to provide precise search results even when the server does not return data in the expected sequence?

Currently, I am in the process of constructing a website for one of my clients. The search page on the site is designed to update search results as you type in the search bar - with each keystroke triggering a new search request. However, there's an i ...

The animation came to a halt after a brief period

Here is the code I wrote. When the button is clicked, the 3 containers should start flashing indefinitely, but they stop after a while. I can't figure out why. Any ideas? <!DOCTYPE html> <html> <head> <title></title> & ...

I'd like some clarification on the code that dynamically adds routes using Typescript and Node Express. Can someone please

Running my API server with node/typescript and express / express validator, I came across this code that I found really useful for separating route logic: function createCustomRouter(route: Array<CustomRouteEntry>): Router { const customRouter = R ...

Reduce the size of your Javascript files to the earliest possible version

Any suggestions for converting minimized JavaScript to earlier versions? Are there any tools or websites available for this task? Thank you in advance for any hints. ...