Recursion

Recursion is a function that calls itself until it doesn’t.

It is better than loops when you have to do multiple nested iterations.
If you would do it with loops you would need to keep track of the index on each nested loop
and gets more complicated to reason about.

Example

  1. let categories = [
  2. {id: 'animals', 'parent': null },
  3. {id: 'mammals', 'parent': 'animals' },
  4. {id: 'cats', 'parent': 'mammals' },
  5. {id: 'dogs', 'parent': 'mammals' },
  6. {id: 'chihuahua', 'parent': 'dogs' },
  7. {id: 'labrador', 'parent': 'dogs' },
  8. {id: 'persian', 'parent': 'cats' },
  9. {id: 'siamese', 'parent': 'cats' },
  10. ];
  11. let makeTree = (categories, parent) => {
  12. let node = {};
  13. categories
  14. .filter(c => c.parent === parent)
  15. .forEach(c =>
  16. node[c.id] = makeTree(categories, c.id));
  17. return node;
  18. }
  19. console.log(
  20. JSON.stringify(
  21. makeTree(categories, null),
  22. null, 2
  23. )
  24. );
  25. // Result
  26. /*
  27. {
  28. "animals": {
  29. "mammals": {
  30. "cats": {
  31. "persian": {},
  32. "siamese": {}
  33. },
  34. "dogs": {
  35. "chihuahua": {},
  36. "labrador": {}
  37. }
  38. }
  39. }
  40. }
  41. */