Arranging items based on parent and child relationships using Angular

In my angular project, I have a dataset that needs to be sorted in a specific way.

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}

I am looking to organize this list within an Angular Material table based on parent-child relationships.

This is the criteria:

If the parentId of an item matches the id of another item, the one with the corresponding parentId should appear below the item with the matching id as its parent value.

The items should be sorted as follows:

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

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

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

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}

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}

I'm seeking help on how to properly implement this sorting logic.

Answer №1

Give this a shot

let dataset = [{ id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4 },
{ id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null },
{ id: 5, name: "111", code: "111", type: 3, hasParent: true, parentId: 4 },
{ id: 4, name: "22", code: "22", type: 1, hasParent: false, parentId: null },
{ id: 3, name: "yyy", code: "yyyy", type: 2, hasParent: false, parentId: null }, 
{ id: 2, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: true, parentId: 1 },
{ id: 1, name: "cbcvb", code: "cvbcvcbv", type: 2, hasParent: false, parentId: null }]; 

let endResult = [];
dataset.forEach((data) => {
    if (endResult.indexOf(data) === -1) {
        endResult.push(data);
    }
    if (data.parentId !== null) {
        let filteredData = dataset.filter(search => {
            return data.parentId === search.id;
        });
        if (endResult.indexOf(filteredData[0]) === -1) {
            endResult.push(filteredData[0]);
        }
    } 
}); 
console.log(endResult);

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

Retrieving JavaScript values using Selenium

I am trying to retrieve these JavaScript values from a web application. var contestPlayResponse = { "winningPrizeIndex" : 1, "playMode" : "NORMAL", "playerId" : "abc123", "gameVersion" : "0-1-86", "gameId" : "blue250k ...

The implementation of a custom event for jQuery rows is not functioning as expected

I need assistance with jQuery code to add click events only to columns in a row that have text in the first column. Specifically, I want to hide rows containing "1/" in the first column when clicked on for the first row. <table class="results"> < ...

Does the gltf loader in three.js have compatibility issues with Internet Explorer 11?

Despite the claims on the official website that gltf files should load in three.js scenes using IE11, I have been experiencing issues with the loader. Even the examples provided by three.js fail to work on Internet Explorer when it comes to loading gltf fi ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Retrieving Form Validation Error Value in AngularJS

Incorporating AngularJS 1.2 RC2 and utilizing Bootstrap for CSS, I have constructed a straightforward form as shown below: <form class="form-horizontal" name="form" novalidate> <label class="col-lg-2 control-label" for="name">Name</labe ...

"Encountering an issue with AngularJS where the selected ng-model value is

I'm utilizing plain options for the select tag because I only need to display a few options when they meet a certain condition. In order to perform other operations, I require the value of the selected dropdown in the controller. However, the issue is ...

Error: The value returned by the function document.getElementById is currently

I am facing an issue with a function that listens for the onkeyup event. This function checks if a box has a value, and if it is not blank, it is supposed to pull the value of an elementID which is a phone number from another page. The function then insert ...

How can I send an object in the query string to a WebAPI?

Can I send a querystring and a model object simultaneously from Angular to WebAPI? The first parameter always gets passed successfully, but the model parameter remains null despite the data being present in the Request Payload. The Model public Class Per ...

Exporting enum in TypeScript declaration file (`.d.ts`) results in a "Unable to resolve" error

yesterday I was updating an enum in our app.d.ts file, which contains most of the app-specific types. The contents of the file are as follows: // app.d.ts export module App { // … more definitions enum MyEnum { A, B, ...

When I click on something else, the dropdown doesn't automatically close

In my current setup, I have 3 dropdowns on the page. When I click outside of any dropdown, they are correctly closed. However, if one dropdown is already open and I click on another one, the previously opened dropdown remains open. I want all dropdowns to ...

What is the command to activate watch mode using ngc?

In the past, using the old tsc method, I could simply call tsc -w and any changed files would be recompiled on the fly. However, with ngc, it seems that the -w flag doesn't have any effect and there is a lack of documentation on its command line argu ...

Generating Ionic components with HTML markup

When I use $http.get to fetch a JSON file, the Ionic view is not displaying the output correctly: loadNews() { return new Promise(resolve => { let header = {"Content-Type": "application/json"}; this.http.get('http://www.mywebs ...

Developing Angular applications with numerous projects and libraries in the build process

The other day I successfully deployed the initial version of our front-end application, but encountered some confusion during the build process setup. Many Angular apps do not utilize the workspace feature unless they are creating multiple standalone appli ...

Issue with serving static files in Angular due to the error encountered with the static file factory definition for the ShepherdService

When attempting to install a project on another computer, which uses Angular version 9.1.0, I encountered an error after running npm install: ERROR in node_modules/angular-shepherd/lib/shepherd.service.d.ts:64:18 - error TS2314: Generic type 'ɵɵFac ...

Understanding ReactJs component syntax: Exploring the nuances and distinctions

Currently diving into the world of Reactjs and working on creating a basic component. I'm puzzled about why this particular syntax for a component: import React, { Component } from 'react'; export default class AboutPage extends Component { ...

Is there a way to determine if a puppeteer instance is already active?

I have a requirement to run multiple puppeteer scripts simultaneously. Up until now, I've been using separate browsers for each script, but now I want to use just one browser with the ability to run multiple scripts concurrently on different pages. M ...

By default, configure the MUI Collapse component to be in a "collapsed" state

I'm currently working on a React/Next/MUI project and I have a query regarding the default setting for the MUI Collapse element. I would like it to be collapsed by default instead of being opened, especially when dealing with large navigations. Here&a ...

An unusual implicit any type discovered in a union with a generic type

When attempting to dynamically infer method parameters, I encounter an issue where an implicit 'any' type is inferred, even though a valid method definition is visible when hovering over the execute method. Renaming either method resolves the pro ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...

Is there a way to change the text (price) when I select an option?

<div class="single-pro-details"> <!--Customize in the CSS--> <h6>Home / Beats</h6> <h4>Unique Lil Tecca Type Beat - New Love</h4> <h2 id="price">$ ...