Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Looking for a better way to extract all parents from a tree object into a simple array

Here's a tree sample fetched via Typeorm:

interface Base {
  id: string;
  name: string;
  parent?: Base;
}

const sample: Base[] = [
  {
    id: "1",
    name: "Son",
    parent: {
      id: "2",
      name: "Father",
      parent: {
        id: "3",
        name: "Grand Father",
      },
    },
  },
];

I want to generate a simple array of all parents from the tree object like this:

const output = [
   {
     id: "2",
     name: "Father",
   },
   {
     id: "3",
     name: "Grand Father",
   }
]

This is my recursive function:

function collect(obj: Base, output: Base[]) {
  if (obj.parent) {
    output = collect(obj.parent, output);
  }
  const { parent, ...rest } = obj;
  output.push(rest);
  return output;
}

let output = [];
output = collect(sample[0], output);

// Use pop to remove the last element which is the "Son" object.
output.pop();

Is there a better way to generate the array? I use the lodash library, would something like _.flatMapDeep work?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There are some minor optimizations possible:

  • Do not expose output array unnecessarily
  • Just start collection one level deeper
  • Recursion is unnecessary
function collect(input: Base) {
  const output = []; // Output contained in function
  let current = input.parent; // Skips self

  while (current != null) { // Loop instead of recursion
    const { parent, ...rest } = current;
    output.push(rest);
    current = current.parent;
  }

  return output;
};

console.log(collect(sample[0]));

Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!