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

128
Views
How can I turn this array structure into this other pattern?

From this:

[["a", "b"], ["a", "c"], ["a", "d"], ["d", "e"], ["d", "f"], ["f", "g"]]

To this:

[["a", "b"], ["a", "c"], ["a", "d", "e"], ["a", "d", "f", "g"]]

The first element of each inner array represents a "father" and the second one a "son", so the final goal is to find grandsons, grandgrandsons... and then group them in bigger arrays, where all descendants are together.

Maybe it's an easy task, but I've been struggling to figure out how to get it!

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

0

If you like to get all relations, without parts which are included in other results, you could get an object of all descendant and start with the parents who are not having parents.

let
    getNodes = k => parents[k]
        ? parents[k].flatMap(getNodes).map(a => [k, ...a])
        : [[k]],
    data = [["a", "b"], ["a", "c"], ["a", "d"], ["d", "e"], ["d", "f"], ["f", "g"]],
    parents = {},
    children = new Set,
    result;


for (const [p, c] of data) {
    (parents[p] ??= []).push(c);
    children.add(c);
}

result = Object
    .keys(parents)
    .filter(p => !children.has(p))
    .flatMap(getNodes);

result.map(a => console.log(...a));

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!