1

I need a recursive function that returns the deepest item first because reversing array and pushing to first position are slow.

I have an object:

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

And a recursive function:

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

  return parents; // [2, 1]
}

I need a recursive function that returns me an array of an objects parent id's so that the last parent is first in the returned array. So for the above example, if I pass in that object into my function, it should return the id's of the parents like this:

[1, 2]
user3743266
  • 1,124
  • 4
  • 16
  • 28

1 Answers1

2
function findParents(myObject, parents = []) {
  if (myObject.parent) {
    parents = findParents(myObject.parent, parents);
  }
  parents.push(myObject.id)
  return parents; // [2, 1]
}
TKoL
  • 13,158
  • 3
  • 39
  • 73