Recursive .reduce() to output an array of parents

javascript parent child recursive
javascript recursive tree search
recursive tree traversal javascript
create a nested array recursively in javascript
recursive function for tree traversal javascript
recursive build tree javascript
javascript recursive function array
how to iterate tree in javascript

I have an flat array of Folders like this one :

const foldersArray = [{id: "1", parentId: null, name: "folder1"}, {id: "2", parentId: null, name: "folder2"}, {id: "1.1", parentId: 1, name: "folder1.1"}, {id: "1.1.1", parentId: "1.1", name: "folder1.1.1"},{id: "2.1", parentId: 2, name: "folder2.1"}]

I want to output an array of all parents of a given folder to generate a Breadcrumb-like component of Folder path.

I have presently a code that does what I need but I'd like to write it better in a more "functional" way, using reduce recursively.

If I do :

      return this.foldersArray.reduce((all, item) => { 
        if ( === folder.parentId) { 
            all.push ( 
         return all
       }, [])

and I log the output, I can see it successfully finds the first Parent, then reexecute the code, and outputs the parent's parent... as my initial array is logically reset to [] at each step... Can't find a way around though...

You could do this with a Map so you avoid iterating over the array each time you need to retrieve the next parent. This way you get an O(n) instead of an O(n²) time complexity:

const foldersArray = [{id: "1", parentId: null, name: "folder1"}, {id: "2", parentId: null, name: "folder2"}, {id: "1.1", parentId: "1", name: "folder1.1"}, {id: "1.1.1", parentId: "1.1", name: "folder1.1.1"},{id: "2.1", parentId: "2", name: "folder2.1"}];
const folderMap = new Map( o => [, o] ));
const getFolderParents = folder => 
    (folder.parentId ? getFolderParents(folderMap.get(folder.parentId)) : [])

// Example call:

Functional JavaScript: Traversing Trees with a Recursive Reduce, Functional JavaScript: Traversing Trees with a Recursive Reduce. Written by James Then we can process trees just as easily as we do arrays (with some caveats, as we'll see). That is, items in children a lot like the parent structure. That is, Tree.reduce() takes a Function, *something, and an Object. Write a program in C++ to print an Array using Recursion Using static variable : Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

You can do what you're looking for with a rather ugly looking while loop. Gets the job done though. Each loop iteration filters, looking for an instance of a parent. If that doesn't exist, it stops and exits. If it does exist, it pushes that parent into the tree array, sets folder to its parent to move up a level, then moves on to the next iteration.

const foldersArray = [{
  id: "1",
  parentId: null,
  name: "folder1"
}, {
  id: "2",
  parentId: null,
  name: "folder2"
}, {
  id: "1.1",
  parentId: 1,
  name: "folder1.1"
}, {
  id: "1.1.1",
  parentId: "1.1",
  name: "folder1.1.1"
}, {
  id: "2.1",
  parentId: 2,
  name: "folder2.1"

function getParents(folder){
	const tree = [], storeFolder = folder
  let parentFolder
  while((parentFolder = foldersArray.filter(t => == folder.parentId)[0]) !== undefined){
    folder = parentFolder
  console.log({ originalFolder: storeFolder, parentTree: tree})


array_walk_recursive - Manual, array_walk() - Apply a user supplied function to every member of an array Since this is only mentioned in the footnote of the output of one of the How to modify external variable from inside recursive function using userdata argument. <?php array_​rand · array_​reduce · array_​replace_​recursive · array_​​replace  So now, if we log the datas object, we can find a parent object as a property of each tree array element ; so we can get the parent of an item. Build the path to an object. We are now set to build the path to the clicked object with a last recursive function :

You're thinking about it in a backwards way. You have a single folder as input and you wish to expand it to a breadcrumb list of many folders. This is actually the opposite of reduce which takes as input many values, and returns a single value.

Reduce is also known as fold, and the reverse of a fold is unfold. unfold accepts a looping function f and an init state. Our function is given loop controllers next which add value to the output and specifies the next state, and done which signals the end of the loop.

const unfold = (f, init) =>
  f ( (value, nextState) => [ value, ...unfold (f, nextState) ]
    , () => []
    , init

const range = (m, n) =>
    ( (next, done, state) =>
        state > n
          ? done ()
          : next ( state        // value to add to output
                 , state + 1    // next state
    , m // initial state

console.log (range (3, 10))
// [ 3, 4, 5, 6, 7, 8, 9, 10 ]

array_merge_recursive - Manual, array_merge_recursive — Merge one or more arrays recursively. Description ¶. array_merge_recursive ([ array $ ] ) : array. array_merge_recursive() merges the elements of one or more arrays together so that the The above example will output: If any value is an array itself, it is merged by parent array, and so on. Given an array of integers, find sum of array elements using recursion. Examples: Input : A[] = {1, 2, 3} Output : 6 1 + 2 + 3 = 6 Input : A[] = {15, 12, 13, 10} Output : 50. We have discussed iterative solution in below post.

JavaScript Get Parent Element parentNode, To get the parent node of a specified node in the DOM tree, you use the The following picture shows the output on Console: JavaScript parentNode. How it works: First, select the element with the .node class by using the querySelector() method. Reduce an Array Into a Value: reduce() · Transform Array Elements: map()  array_walk_recursive (PHP 5, PHP 7) array_walk_recursive — Apply a user function recursively to every member of an array

Program for length of a string using recursion, 788 MST-KRUSKAL 525 MST-PRIM 527 MST-REDUCE 532 MULTIPOP 376 283 P-FIB 646 P-MATRIX-MULTIPLY-RECURSIVE 661 P-MERGE 666 P-​MERGE-SORT 673 P-SQUARE-MATRIX-MULTIPLY 659 P-TRANSPOSE 659 PARENT 124 855 PRINT-LCS 329 PRINT-OPTIMAL-PARENS 314 PRINT-​PATH 501  In the recursive term of the query, we add new entries from the base table, and we also maintain our local state: the computed columns parents (an array of id values) and level (an integer that increments at each step). When using PostgreSQL, the concatenation operator works on text values and on array values too,

Thinking Recursively in Python – Real Python, Given a string calculate length of the string using recursion. Examples: Input : str = "abcd" Output :4 Input : str = "GEEKSFORGEEKS" Output :13 int main(). {. char str[] = "GeeksforGeeks" ;. cout << recLen(str);. return 0;. } C++ Program to print an Array using Recursion · Program to check if an array is palindrome or not using  We have discussed simple BST insert.How to insert in a tree where parent pointer needs to be maintained. Parent pointers are helpful to quickly find ancestors of a node, LCA of two nodes, successor of a node, etc.