Skip to content

Instantly share code, notes, and snippets.

@bartdorsey
Last active September 16, 2022 15:25
Show Gist options
  • Save bartdorsey/8819c5b26faffee1d78e454a7fce3df1 to your computer and use it in GitHub Desktop.
Save bartdorsey/8819c5b26faffee1d78e454a7fce3df1 to your computer and use it in GitHub Desktop.
Make Tree

Make Tree

This problem was inspired by a Fun Fun Function video: https://www.youtube.com/watch?v=k7-N8R0-KY4

Write a recursive function makeTree(categories, parent) that takes an array of categories objects, each of which have an id property, and a parent property and returns a nested tree of those objects using the parent properties to construct the tree.

A parent value of null means you are at the bottom of the tree and the category has no parent, so the default value parent is be null if no parent is provided.

Example 1:

Given an array of objects with id properties to create our tree:

const categories1 = [
    { id: 'animals', 'parent': null },
    { id: 'mammals', 'parent': 'animals' }
];

const tree1 = makeTree(categories1, null);

We should return a tree like this:

{
  animals: {
    mammals: {}
  }
}

Example 2:

Now imagine we have a database that returns a bunch of rows of data:

const categories2 = [
    { id: 'animals', 'parent': null },
    { id: 'mammals', 'parent': 'animals' },
    { id: 'cats', 'parent': 'mammals' },
    { id: 'dogs', 'parent': 'mammals' },
    { id: 'chihuahua', 'parent': 'dogs' },
    { id: 'labrador', 'parent': 'dogs' },
    { id: 'persian', 'parent': 'cats' },
    { id: 'siamese', 'parent': 'cats' }
];

Then we call the function with the categories:

const tree2 = makeTree(categories2, null);

The call above should return the tree below:

{
    animals: {
        mammals: {
            dogs: {
                chihuahua: {},
                labrador: {}
            },
            cats: {
                persian: {},
                siamese: {}
            }
        }
    }
}

Solution

const makeTree = (categories, parent) => {
  // At each level of the tree, we create a node object
  const node = {};
  // We filter the category list for categories where
  // the category's parent property matches the parent we
  // were passed in.
  const matchingCategories = categories.filter((category) => {
    return category.parent === parent;
  });

  // Then we loop through each of the matching categories
  matchingCategories.forEach((category) => {
    // and set a property on the node with the key
    // of the category.id and the value as the result
    // of calling makeTree recursively to handle the next
    // category down.
    node[category.id] = makeTree(categories, category.id);
  });
  // We return the node at the end, so it will get stored
  // on the parent node in the tree.
  return node;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment