Clearing all the nested offspring elements within a highly nested one-dimensional array

I am working with a 1D deep nested array structure:

nestedObj: [
   { id: 1, parentId: null, taskCode: '12', taskName: 'Parent one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 2, parentId: 1, taskCode: '12100', taskName: 'Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 3, parentId: 2, taskCode: '12200', taskName: 'SubChild one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 4, parentId: 3, taskCode: '122001', taskName: 'Sub-dub-Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 5, parentId: null, taskCode: '13', taskName: 'Parent two', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}
]

In the above data structure, the tree view with taskName displayed is as follows:

-> Parent one
        -> Child one
                   -> SubChild one
                                  ->Sub-sub-Child one
-> Parent two     

If I were to remove a node (let's say Parent one), then all its nested children (up to Sub-sub-Child one) should also be deleted. How can I achieve this using recursion?

Thank you for your help

Answer №1

const nestedData = [
   { id: 1, parentId: null, taskCode: '12', taskName: 'Parent one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 2, parentId: 1, taskCode: '12100', taskName: 'Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 3, parentId: 2, taskCode: '12200', taskName: 'SubChild one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 4, parentId: 3, taskCode: '122001', taskName: 'Sub-dub-Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 5, parentId: null, taskCode: '13', taskName: 'Parent two', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}
];
function recursivelyRemove(id) {
  const index = nestedData.findIndex((element) => element.id === id);
  if (index === -1) return;
  
  nestedData.splice(index, 1);
  
  const childElements = nestedData.filter((element) => element.parentId === id);
  for (const element of childElements) {
    recursivelyRemove(element.id);
  }
}

recursivelyRemove(2);
console.log(nestedData);

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

Unable to trigger click event on dynamically added element using Chrome (jQuery)

My approach here involves dynamically creating a drop-down and binding the click event to the <option> within the <select> var $select = $('<select></select>'), $option1 = $('<option>a</option>') ...

Create a login dropdown menu with HTML, CSS, and JavaScript without the need

Hello, I need help finding a dropdown login/menu that doesn't rely on bootstrap-like CSS or jQuery. Unfortunately, my school prohibits their use. The menu should be compact and preferably appear when clicking or hovering over the login button located ...

The vue-croppa component is showing unusual behavior, with an error message stating "Failed to mount component: template or render function not

I recently tried utilizing vue-croppa for image cropping in my project. I installed it using the npm package manager with the command: npm install --save vue-croppa However, when attempting to implement it as usual: import Croppa from 'vue-croppa&a ...

Utilizing React, Graphql, and Next.js, you can expect to receive an object or JSON value instead of the

Presently, I am viewing an object output of {value=1, label=USA} https://i.sstatic.net/MLeIT.png However, I would like to only access the label output USA on my-post page On the create-post page, I am able to access post.countries ? countries.label : &qu ...

Can React Slick be configured to display a Carousel within another Carousel?

Can React Slick support a Carousel within another Carousel? import Slider from "react-slick"; <Slider {...settings} > <div/> <div> <Slider {...settings} > ...

Ordering results based on function output within a v-for loop in Vue.js

In my code, I have an array that I am looping through in the following way: <template v-for="plan in plans"> ... </template> My goal is to sort the plans array by a calculation based on certain properties of each plan. Let's ...

Having trouble displaying the image in my administrative tool

I am currently developing an admin application that will showcase uploaded product images stored in a database. The images are saved as object IDs in MongoDB. However, the image container in the admin app shows the count of images stored in the database bu ...

The React properties continue to update, even when I am not actively utilizing them

I created a project using the create-react-app template. I am facing an issue with importing data from a JSON file and sending it to the Todos component file as props. Although I am not using it as a prop in the Todos file, the todo list updates when I use ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

Combining the power of jQuery, PHP, JavaScript, and the popular WordPress platform, let's unlock

After going through numerous attempts to find answers for similar issues, I'm unable to get any of the suggested solutions to work. My WordPress site requires a plugin that utilizes jQuery. The main file for my plugin is located at wp-content/plugins ...

The document inside the database is displayed in italicized text when it is stored in Firebase

try { // establish a new collection named 'pactLists' const pactListsCollection = collection(db, "pactLists"); // used for storing records of created pacts by users. // generate a unique id for the pact and set it as the invite c ...

Ways to modify or conceal the __nuxt and __NUXT__ term in webpage source code

Can the automatically generated __nuxt and __NUXT keywords in the page source be modified or concealed when using Nuxt.js? https://i.stack.imgur.com/GZlxC.png ...

Unable to load connected modules from npm/yarn link within the WSL environment

Trying to import a local dependency into my project is proving to be quite challenging. The situation at hand involves a project named 'test_project' and another one called 'test_module'. Linking test module to the global node_modules ...

The placement of the FirebaseAuth.onAuthStateChanged call in an Angular application is a common concern for developers

Where is the best place to add a global listener initialization call in an Angular app? Take a look at this code snippet: export class AuthService { constructor( private store: Store<fromAuth.State>, private afAuth: AngularFireAuth ) { ...

Display or conceal a button in Angular 6 based on certain conditions

In my current project, I am facing a challenge where I need to disable a button while a task is running and then activate it once the task is complete. Specifically, I want a syncing icon to spin when the task status is 'In_progress' and then hid ...

When you try to upload an image using php/ajax, it causes the page to refresh

I'm currently experiencing an issue with my script. I am successfully using formData() to upload an image via Ajax, which is being saved to the designated folder. However, I am puzzled as to why my page keeps refreshing after move_uploaded_file() is e ...

What is the reason behind TypeScript's lack of support for exporting with decorators?

The issue regarding this problem was addressed on https://github.com/tc39/proposal-decorators/issues/69. Despite this discussion, TypeScript does not currently support it. The following code demonstrates the lack of support: export @deco() class a {}; H ...

Angular 2 orderByPipe not displaying any results initially

At first, I thought the reason for not displaying anything initially was due to it not being async and returning an empty array. Everything worked fine without the pipe, but the posts weren't shown on startup. After submitting a post, all the posts ap ...

Tips for showcasing JSON data within an array of objects

I'm trying to work with a JSON file that has the following data: {"name": "Mohamed"} In my JavaScript file, I want to read the value from an array structured like this: [{value: "name"}] Any suggestions on how I can acc ...