Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver corresponds to the current ID, Antenna is from the parentID of Receiver, and MotherBoard is from the parentID of Antenna.

What recursive approach would be most effective in achieving this new array?

The current code provided below is not successfully producing the desired outcome.

const newArray: string[] = [];
    for (const feature of featureList) {
      if (feature.id === this.featureId) {
        newArray.push(feature.name);
        if (feature.parentFeatureId) {
          for (const parentFeature of featureList) {
            if (parentFeature.id === feature.parentFeatureId) {
              newArray.push(parentFeature.name);
            }
          }
        }
      }
    }


  var featureList = [
      {
        "id": 1,
        "name": "MotherBoard",
        "projectId": 1,
        "parentFeatureId": null
      },
      {
        "id": 2,
        "name": "Power Supply",
        "projectId": 1,
        "parentFeatureId": 1
      },
      {
        "id": 3,
        "name": "Antenna",
        "projectId": 1,
        "parentFeatureId": 1
      },
      {
        "id": 4,
        "name": "Transmitter",
        "projectId": 1,
        "parentFeatureId": 3
      },
      {
        "id": 5,
        "name": "Receiver",
        "projectId": 1,
        "parentFeatureId": 3
      },
      {
        "id": 6,
        "name": "Storage",
        "projectId": 1,
        "parentFeatureId": null
      },
      {
        "id": 7,
        "name": "Calibration State",
        "projectId": 1,
        "parentFeatureId": 6
      },
      {
        "id": 8,
        "name": "User Profile mgm",
        "projectId": 1,
        "parentFeatureId": 6
      },
      {
        "id": 9,
        "name": "HW State mgm",
        "projectId": 1,
        "parentFeatureId": 6
      }
    ]

Answer №1

If you're looking to generate a list of parent names for a specified ID using recursion, here's a function you can use:

var getParents = function(id){
  var currentFeature = featureList.find(element => element.id === id);
    if (currentFeature && currentFeature.parentId)
      return [...getParents(currentFeature.parentId), currentFeature.name]
    else if (currentFeature)
      return [currentFeature.name];
    else
      return [];
};

This function takes the provided ID, searches for the corresponding object in featureList, and then creates an array containing the names of all parent features leading up to the specified object. The function uses recursion by calling itself with the parent ID.

For more information, visit https://jsfiddle.net/ps1ks89a/16/.

Answer №2

To solve this problem in vanilla JavaScript, you can implement a recursive solution that considers the current index and keeps track of visited feature names.

When the target item is found, the function returns the list of collected names.

This method relies on a sorted list where parents precede their children.

function getFeatures(id, array, parent = null, index = 0, features = []) {
    var temp;
    while (index < array.length) {
        if (array[index].parentFeatureId !== parent) {
            index++;
            continue;
        }
        if (array[index].id === id) {
            return features.concat(array[index].name);
        }
        temp = getFeatures(id, array, array[index].id, index + 1, features.concat(array[index].name));
        if (temp) {
            return temp;
        }
        index++;
    }
}

var featureList = [{ id: 1, name: "MotherBoard", projectId: 1, parentFeatureId: null }, { id: 2, name: "Power Supply", projectId: 1, parentFeatureId: 1 }, { id: 3, name: "Antenna", projectId: 1, parentFeatureId: 1 }, { id: 4, name: "Transmitter", projectId: 1, parentFeatureId: 3 }, { id: 5, name: "Receiver", projectId: 1, parentFeatureId: 3 }, { id: 6, name: "Storage", projectId: 1, parentFeatureId: null }, { id: 7, name: "Calibration State", projectId: 1, parentFeatureId: 6 }, { id: 8, name: "User Profile mgm", projectId: 1, parentFeatureId: 6 }, { id: 9, name: "HW State mgm", projectId: 1, parentFeatureId: 6 }]

console.log(getFeatures(5, featureList));

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 prompt npm to install a sub-dependency from a GitHub pull request?

Currently, I'm in the process of setting up geofirestore, which has a dependency on geofirestore-core. However, there is an existing bug in geofirestore-core that has been addressed in a pull request. How can I make sure that my geofirestore installa ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Guide on incorporating secondary endpoints to develop an API for an Angular library

Challenge: I recently developed a customized UI library using ng-packagr, where I exported unique components along with some model classes. Issue: While the import statement functions correctly for the exported components in my main project, it fails to ...

Turning On/Off Input According to Selection (Using jQuery)

<select name="region" class="selection" id="region"> <option value="choice">Choice</option> <option value="another">Another</option> </select> <input type="text" name="territory" class="textfield" id="territo ...

Retrieve all exports from a module within a single file using Typescript/Javascript ES6 through programmatic means

I aim to extract the types of all module exports by iterating through them. I believe that this information should be accessible during compile time export const a = 123; export const b = 321; // Is there a way to achieve something similar in TypeScript/ ...

"Troubleshooting: Ajax File Uploader Plugin Not Functioning Properly

Today, our web site's file upload feature using the javascript plugin Simple-ajax-uploader suddenly stopped functioning (09/05/2019). The upload div/button is unresponsive when clicked. This issue is not limited to our site; even the official plugin ...

After a page reload, Material-UI stops functioning properly

I am currently working with Material UI in a Next.js project. When I run npm run dev, everything looks good. However, whenever I refresh the page, all the styling breaks. Has anyone experienced this issue before? It seems like Material-UI is no longer func ...

Is there a way to add pins to separate entity layers, and then remove them from a specific entity layer using Bing Maps AJAX Control, Version 7.0?

Currently, I am utilizing Bing Maps to display store locations on a map. The information about the stores is coming from a dynamic JSON response. When the page loads, the map shows local stores with pushpins and infoboxes. As the map pans, my goal is to re ...

Sophisticated Sidebar Design using Bootstrap 5

Looking to design a responsive sidebar for navigation on my page, with selected and hover properties. Visualizing the selected option to appear like this: Selected (active) option in sidebar The goal is to have the image cover the left side of the backgr ...

Executing window.open from Html.Actionlink in ASP.NET MVC 4

Here is the code block I am working with: @foreach (System.Data.DataRow drEquipment in Model.EquipmentList.Rows) { <tr> <td valign="top">@drEquipment["ColumnName"]<br /></td> <td valign="to ...

Tips on extracting the ID number prior to locating an element by its ID using Python Selenium

I am currently attempting to automate sending LinkedIn connection requests using Python with Selenium. However, I am facing an issue where the ember number value keeps changing every time I try to copy the id of the button. Sometimes it shows as #@id=" ...

Guide to utilizing @types/node in a Node.js application

Currently, I am using VSCode on Ubuntu 16.04 for my project. The node project was set up with the following commands: npm init tsc --init Within this project, a new file named index.ts has been created. The intention is to utilize fs and readline to read ...

The POST variable consistently remains void

The approach I am using to handle the data sent with jquery.ajax involves sending an empty string by default. Whenever there is a change, I monitor the input for changes and resend the data. Everything seems to work fine in the console, but in PHP, $this-& ...

Converting HTML to a Text String (not for display) using Angular

When it comes to displaying HTML in Angular, there are numerous approaches available. For example, using $sce.trustAsHtml(myHtmlVariable) is one way to achieve this. However, I am interested in creating something like the following: myStringVariable = s ...

Having trouble with assigning an error message in Formik validation using TypeScript

Currently, I am in the process of constructing a user input form in React & TypeScript using Formik. The form requires the user to input a name, email, and password. The input handling is functioning properly, but now I aim to implement validation functio ...

Silky animations in kinetic.js (html5 canvas)

I am seeking a better grasp on kinetic.js animation. Recently, I came across a tutorial at . After experimenting with the code provided, I managed to create an animation that positions my rectangle at x coordinate 100. However, I am struggling to achieve s ...

Enhance the current MultiSelect object by incorporating JQuery MultiSelect

Is there a way to detect changes on a JQuery MultiSelect in order to trigger an update elsewhere? The typical javascript onchange method does not seem to work because the select itself does not change. However, I came across a method called "beforeclose" t ...

Basic math tool using JSP/Servlet combination and Ajax

I have a follow-up question to my previous inquiry on Stack Overflow. I believe this topic deserves its own discussion due to the thorough response I received. My goal is to develop a straightforward calculator using JSP. The calculator will include two t ...

Javascript - understanding variable scope

Hey there! I have some code that I need help with var idx = 0; var size = 0; do { response.push({ key: "data" + idx, ajaxOptions: function () { var data = this.getPref("groupsCN"); var items = data.split('; ...

When utilizing the vue @submit directive, the FormData object may be found to be devoid

Encountering a unique edge case, I found a solution. When creating a form with Vue, I noticed that empty strings were being sent to the server. Upon investigation, it became apparent that the issue lies within the @submit directive. Interestingly, when uti ...