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 => === folderId);

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

125 thoughts on “es6 generate path to root node using parent ids”

  1. i need loan urgently in dubai, i need a loan desperately today. i need a loan have no credit need loan now need a loan fast i need quick loan, cash advance loans near me, cash advance, cash advance loans, western union cash advance loans. Investment have acquired investment, provides business loans.


Leave a Comment