es6 generate path to root node using parent ids

I have a flat array of items, each with a parent id. I would like to write an es6 function that can return an array of strings with the item’s name from the current item to the root (the root is defined as the item with id = 0 or parent id === -1). The array is not necessarily ordered.

// items
const items = [
  { id: 0, parentId: -1, name: 'root' },
  { id: 1, parentId: 0, name: 'first folder' },
  { id: 2, parentId: 0, name: 'another folder' },
  { id: 3, parentId: 0, name: 'yet another folder' },
  { id: 4, parentId: 1, name: 'my folder' },
  { id: 5, parentId: 3, name: 'my other folder' },
  { id: 6, parentId: 4, name: 'this folder' },
];

So if I started from item with id = 6, I would get in return

[ 'root', 'first folder', 'my folder', 'this folder']

I have tried a recursive solution with no luck but an answer does not need to be recursive, just clean code.

export const getFolderPath = (folderId, folders, path = []) => {

  if (folderId === '0') return ['root', ...path];

  const folder = folders.find(folder => folder.id === folderId);

  return getFolderPath(folder.parentId, folders, [...path, folder.name]);
};

1 thought on “es6 generate path to root node using parent ids”

  1. Turn the array into an object indexed by ID, and then recursively go through the .parentId on the object:

    const items = [
      { id: 0, parentId: -1, name: 'root' },
      { id: 1, parentId: 0, name: 'first folder' },
      { id: 2, parentId: 0, name: 'another folder' },
      { id: 3, parentId: 0, name: 'yet another folder' },
      { id: 4, parentId: 1, name: 'my folder' },
      { id: 5, parentId: 3, name: 'my other folder' },
      { id: 6, parentId: 4, name: 'this folder' },
    ];
    
    const itemsById = Object.fromEntries(
      items.map(item => [item.id, item])
    );
    
    const final = 6;
    const recurse = (id, names = []) => {
      const parent = itemsById[id];
      if (!parent) return '';
      recurse(parent.parentId, names);
      names.push(parent.name);
      return names;
    };
    console.log(recurse(6));
    Reply

Leave a Comment