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]