I am trying to write a function in javascript that from JSON input data returns the data belonging to a specific group, including the children of that group. The data looks like this:
[
{"id":"0", "name":"Person 0"},
{"id":"1", "name":"Person 1","group":"0"},
{"id":"2", "name":"Person 2","group":"0"},
{"id":"3", "name":"Person 3","group":"2"},
{"id":"4", "name":"Person 4","group":"2"},
{"id":"5", "name":"Person 5","group":"4"},
{"id":"6", "name":"Person 6","group":"4"},
{"id":"7", "name":"Person 7","group":"0"},
{"id":"8", "name":"Person 8","group":"7"}
]
Here, a person in group x belongs to the same group as person with id x.
For example: function(data, group) would return the following for function(data, 2):
[
{"id":"3", "name":"Person 3","group":"2"},
{"id":"4", "name":"Person 4","group":"2"},
{"id":"5", "name":"Person 5","group":"2"},
{"id":"6", "name":"Person 6","group":"2"},
]
and function(data,0):
[
{"id":"1", "name":"Person 1","group":"1"},
{"id":"2", "name":"Person 2","group":"2"},
{"id":"3", "name":"Person 3","group":"2"},
{"id":"4", "name":"Person 4","group":"2"},
{"id":"5", "name":"Person 5","group":"2"},
{"id":"6", "name":"Person 6","group":"2"},
{"id":"7", "name":"Person 7","group":"7"},
{"id":"8", "name":"Person 8","group":"7"}
]
I have tried to loop through the array but that doesn’t deal with the subgroups, so I guess I have to do it in a recursive fashion?
You can
.reduce()the data array and concatenate in the sub groups.Hopefully there are no circular references!
Though I don’t understand thegroup(data, 0)output, and I don’t see any sub-group data.