Reorder the items recursively to have the last item appear first

Seeking a recursive function that retrieves the deepest item first due to performance concerns with reversing arrays and pushing them to the first position.

An example object:

const myObject = {
    id: 3,
    parent: {
        id: 2,
        parent: {
            id: 1,
            parent: null,
        },
    },
};

The provided recursive function is as follows:

function findParents(myObject, parents = []) {
  if (myObject.parent) {
    parents.push(myObject.parent.id);
    return findParents(myObject.parent, parents);
  }

  return parents; // [2, 1]
}

I am in need of another recursive function that will output an array containing the ids of the object's parents, with the last parent appearing first in the returned array. Using the above object as an example, the desired output should be:

[1, 2]

Answer №1

function retrieveAncestors(obj, ancestors = []) {
  if (obj.parentNode) {
    ancestors = retrieveAncestors(obj.parentNode, ancestors);
  }
  ancestors.push(obj.identifier)
  return ancestors; // [2, 1]
}

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

AngularJs Resource provides the functionality to pass optional parameters through the URL

Currently, I am utilizing this type of resource: var Products = $resource('companies/:companyId/products') However, the issue arises when I attempt to access the products from all companies via the URL companies/products. Instead of receiving the ...

Obtain all the child roles' "User" entities

There are six roles in the project: Super Admin - Has the ability to create Sub super admin, Admin, Super Master, Master, and User. Sub Super Admin - Can create Admin, Super Master, Master, and User. Admin - Able to create Super Master, Master, and User. ...

jQuery validation - Date not validated on Safari, only works on Chrome

Issue: jQuery validation is not functioning properly on Safari, but it works fine on Google Chrome and Firefox. The content management system (CMS) responsible for handling the form signup requires the date to be in the format YYYY-MM-DD. However, most pe ...

Conceal the parent element if there are no elements present within the child element

Look at the markup provided: <div class="careersIntegration__listing" id="careers-listing"> <div class="careersIntegration__accordion"> <div class="careersIntegration__accordion-header"> <span class="careersIntegrat ...

Load jQuery script after Ajax call has loaded the filter

Currently, I have multiple jQuery scripts running on one page. This specific page includes a product filter that operates using ajax. You can view the product filter at Below is one of the scripts I am utilizing: var $s = jQuery.noConflict(); $s('bo ...

Screen a collection of strings based on the matching character at the corresponding position

In an attempt to create a basic function that takes in three inputs: a list of words, a list of guessed letters, and a pattern. The pattern represents a word with certain letters hidden as underscores (for example, the word "apple" and the pattern "_pp_e") ...

Error encountered when attempting to dynamically alter property values of an object using Typescript

Can anyone help me figure out how to dynamically change object property values based on the property type in Typescript? I want to replace all string properties with "***", but I keep running into an error that says Type '"***"' is not assignable ...

Locate the key within an array and display the corresponding value

I'm working with a sizable PHP array that contains the following data snippet. Is there a way to efficiently search through this array and retrieve the value of "date" without having to iterate through all its elements? It's worth mentioning tha ...

"Trouble with Vue chart.js: Data not loading properly when the page

I'm currently working on a project that involves using vue-chartjs within the Laravel framework. I've encountered an issue where the data doesn't load upon initial page load. However, if I click on the Legend three times, the data eventually ...

Initiate CSS animation upon modification of component properties

I am looking for a way to create a fade in/out effect on a component whenever its prop changes. Unlike basic examples that toggle styles based on boolean conditions, I want the element's visibility state to be updated directly through prop changes. F ...

implementing AJAX functionality in Laravel when a drop-down item is selected

Hello there, I am a newcomer to the world of coding and I'm currently learning Laravel for a personal project. My goal is to retrieve data from a database based on the selection made in a dropdown menu. Here's the code for the dropdown menu: < ...

PHP: When an Array Key is Not Defined

https://i.sstatic.net/k2d1Z.png This is the result I am trying to organize and display my data in tables based on the date. I have stored the data from the database in an array for this purpose. However, I am encountering an error warning stating 'un ...

How do I incorporate global typings when adding type definitions to an npm module?

Suppose I create a node module called m. Later on, I decide to enhance it with Typescript typings. Luckily, the module only exports a single function, so the m.d.ts file is as follows: /// <reference path="./typings/globals/node/index.d.ts" /> decl ...

Is it possible to integrate ng-repeat with ng-model in Angular?

Is it possible to link the ng-model of a button with the ng-repeat loop? <a ng-repeat="x in [1,2,3,4]" ng-model="myButton[x]">{{myButton[x]}}</a> In the Controller: var id = 4; $scope.myButton[id] = ' :( '; I am interested in crea ...

Enhancing Communication between Sibling Components in Angular 2

I have a ListComponent where clicking on an item should display its details in DetailComponent without any routing involved. Both components are displayed simultaneously on the screen. How can I pass the information of the clicked item from ListComponent ...

Guide on generating a unique X and Y rotation for every object created randomly in Three JS

I've been working on a personal project using Three JS as my main 3D object renderer. I'm trying to randomly generate spheres at various x, y, and z coordinates within a specified range. I was able to achieve this, but now I want each of these ob ...

Learn how to organize a div element containing select options using categories such as gender and shoe size, similar to the filtering

Is there a way to sort div elements using a select menu, similar to how it is done on shopping websites? I am struggling with modifying my JS code in order to implement multiple selects. Although I believe my JS code is correct, it doesn't seem to be ...

AngularJS pagination with filtering

Currently, I am using ng-paginate for pagination on my website. However, I have encountered a problem when applying filters. Specifically, I have a dropdown menu with 3 different options to choose from. The issue arises when I select an option from the dr ...

AngularJS - Not binding $scope to the DOM

Recently starting out with Angular, I decided to practice by creating a simple website. One of the features I want to include is displaying the number of times a button has been clicked through data binding. Here's the controller code I've writte ...

attribute alternativeType

<input type="text" name="date" value="" data-type="datetime" required="true" /> I'm looking for a different approach than using dojoType for a couple of reasons: The parseonload behavior causes the page to "jump" when loading (system-defaul ...