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

Is it possible to optimize the performance of my React and TypeScript project with the help of webpack?

I am working on a massive project that takes 6 to 8 minutes to load when I run npm start. Is there a way to speed up the loading process by first displaying the sign-in page and then loading everything else? ...

Employing live labels on a Morris Bar Chart

I'm using the Morris Bar Chart to showcase the sales of different products. To enhance user experience, I want to display dynamic labels when hovering over the bars. The data is being fetched through PHP. array('product' => $row['pr ...

"Unlocking Angular event intellisense in Visual Studio Code: A Step-by-Step Guide

Currently, I am enrolled in an Angular course on Udemy. The instructor prefers using VS Code as his code editor, and one interesting feature he showcased was when he tried to add events to a button element. As soon as he opened the parenthesis after the bu ...

What is the most effective way to integrate a Link/URL button into the remirror toolbar?

I have chosen to utilize remirror for constructing a WSYWIG editor. The specific requirement is to include a "Link" icon in the toolbar, allowing users to select text and easily add a hyperlink by clicking on it. Although I came across the LinkExtension ...

Angular 4 lazy loading feature is malfunctioning

I've been working on implementing lazy loading in my angular4 project, following all the steps outlined in the documentation without success. Here is a snippet of my code: StudentModule: import { NgModule } from '@angular/core'; import { ...

AngularJS ng-model not refreshing

One of the features in my application is a Font Awesome icon picker that allows employees to easily access different icons without having to search for their codes online. However, I am facing an issue where clicking on an icon does not update the ng-mode ...

Incorporating a computed variable in a v-select within a VueJs endless loop

I've been attempting to utilize a computed value in a v-select component from Vuetify, but every time I select an item, it triggers an endless loop. To demonstrate the issue, I have recreated my code in this CodePen. Please be cautious as it may caus ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

The validation of form.$invalid appears to be malfunctioning when using the Angular UI date picker

There are two fields on the form, one for selecting a due date and another for entering a number. The due date field is a date picker where you can choose a date or manually enter a number to set the date. The create button gets enabled only when setting ...

Different ways to notify a React/Next.js page that Dark Mode has been switched?

I am in the process of creating my first basic Next.js and Tailwind app. The app includes a fixed header and a sidebar with a button to toggle between dark and light modes. To achieve this, I'm utilizing next-theme along with Tailwind, which has been ...

An unexpected page transition occurs when attempting to delete a link

I've successfully created an HTML table that dynamically adds rows and provides an option to delete the current row. Each row represents data retrieved from MongoDB, and upon clicking the delete button, I aim to delete the corresponding item from the ...

Utilize jQuery and HTML simplistically to display or conceal divs throughout a webpage

After developing some basic jQuery code using if-statements to toggle the visibility of Divs based on a select list in HTML, I am seeking ways to enhance this code: 1) How can I achieve the same functionality with fewer lines of code? 2) Rather than manu ...

I'm looking to add CSS transitions, like fade-ins, to a list of items in React in a way that the animations occur one after the other upon rendering. How can this be achieved?

I've scoured the depths of Stack Overflow and combed through countless pages on the internet in search of an answer to my query, but alas, I have not found a solution. So, my apologies if this question is a duplicate. Here's my conundrum: https ...

Struggling with Getting My Animation to Function Correctly

I am trying to create a JQuery Animation that will move a div covering a text box up into the border when clicked. Despite multiple attempts, I can't seem to get the animation to work properly. Any suggestions? JavaScript function moveup(title,text ...

Using React Native, you can easily apply styles to View components by passing them

Is it a bug? Or is the View styles props object supporting inline props as well? For example, in the traditional way and also written in React Native documentation: function App() { return ( <View style={styles.box}></View> ) } const ...

Uncover the valuable information within a string using regex in JavaScript

I am looking for a solution to extract key values from a string that looks like this: <!-- Name:Peter Smith --><!-- Age:23 --> My goal is to create a standard function that can extract any value needed. The function call would be something like: var ...

Checking to see if the prop 'isChecked' has been modified

I'm currently facing a challenge with testing whether a class's prop value changes after clicking the switcher. Below is the component class I am working with: import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core&a ...

Issue with Redirecting in React: REST requests are not successful

There's a text input that triggers a submission when the [Enter Key] is pressed. const [ query, setQuery ] = React.useState('') ... <TextField label="Search Codebase" id="queryField" onChange={ event => setQuery( ...

Is it possible to showcase a unique date for every item that gets added to a list?

I am new to using React, so please bear with me. I want to be able to show the date and time of each item that I add to my list (showing when it was added). I am struggling to get this functionality working with my current code. Any help or explanation o ...

Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML <select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names" class="code-helper" id="code-helperId"> <option value="">Select Option</op ...