I have multiple trees, for example:
a h
| \ |
b c i
/ | \ / \
d e f j k
| / | \
g l m n
which represented in a single JavaScript object like this:
{ 'a': ['b', 'c'],
'b': null,
'c': ['d', 'e', 'f'],
'd': null,
'e': ['g'],
'f': null,
'g': null,
'h': ['i'],
'i': ['j', 'k'],
'j': ['l', 'm', 'n'],
'k': null,
'l': null,
'm': null,
'n': null }
i.e. all the nodes appears as keys, and the value of a particular key/node is an array of all its children (or null if it doesn’t have children).
I would like to construct two things:
-
An array of all roots. In this example:
['a', 'h'] -
For every root, an array of all its descendants, including the root. In this example:
['a', 'b', 'c', 'd', 'e', 'f', 'g']['h', 'i', 'j', 'k', 'l', 'm', 'n']
The order of the elements in the resulting arrays doesn’t matter.
Could you suggest an elegant method to implement this in JavaScript (jQuery allowed).
As a result
rootsvariable contains next value for your second task:And for your first task
Object.keys(roots)returns needed array.