@benjaminconant/

BriskLimeSchipperke

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function printTreeLevels (startingNode) {

  // This will be a multi-dim array of "level" arrays, each containing values
  var levels = [];

  // recursive IIFE to collect each value and add it to the right level array
  (function collectVals (node, level) {
    // if there is no level this deep yet, make it
    levels[ level ] = levels[ level ] || [];
    levels[ level ].push( node.value );
    // recursively handle each child node, one level deeper
    node.children.forEach(function (childNode) {
      collectVals( childNode, level+1 );
    });
  })( startingNode, 0 );

  // Print the results
  levels.forEach(function (level) {
    console.log( level.join(' ') );
  });

}

/* A sample tree to test, should print the following:
A
B C
D E F G
H I J
*/

var myTree = {
  value: 'A',
  children: [{
    value: 'B',
    children: [{
      value: 'D',
      children: [{
        value: 'H',
        children: []
      }]
    }]
  }, {
    value: 'C',
    children: [{
      value: 'E',
      children: []
    }, {
      value: 'F',
      children: [{
        value: 'I',
        children: []
      }, {
        value: 'J',
        children: []
      }]
    }, {
      value: 'G',
      children: []
    }]
  }]
};

printTreeLevels(myTree);

Native Browser JavaScript