Answer the question
In order to leave comments, you need to log in
How to get a subtree of a given node if the tree nodes are in an array?
There is an array of hashes that describe a tree, each element of the array has its own id
parent id
:
arr = [
{id: 23, title: 'aaa', parent_id: nil},
{id: 24, title: 'aab', parent_id: 23},
{id: 25, title: 'aac', parent_id: 23},
{id: 26, title: 'aad', parent_id: 25},
{id: 27, title: 'aae', parent_id: 25},
{id: 28, title: 'aaf', parent_id: 27},
{id: 29, title: 'aag', parent_id: 27},
{id: 30, title: 'aah', parent_id: 24},
{id: 31, title: 'aaz', parent_id: 24},
]
{id: 24, parent_id: 23
}. The method should return[
{id: 30, title: 'aah', parent_id: 24},
{id: 31, title: 'aaz', parent_id: 24},
]
{id: 25, parent_id: 23}
. The method should return[
{id: 26, title: 'aad', parent_id: 25},
{id: 27, title: 'aae', parent_id: 25},
{id: 28, title: 'aaf', parent_id: 27},
{id: 29, title: 'aag', parent_id: 27}
]
Answer the question
In order to leave comments, you need to log in
arr = [
{id: 23, title: 'aaa', parent_id: nil},
{id: 24, title: 'aab', parent_id: 23},
{id: 25, title: 'aac', parent_id: 23},
{id: 26, title: 'aad', parent_id: 25},
{id: 27, title: 'aae', parent_id: 25},
{id: 28, title: 'aaf', parent_id: 27},
{id: 29, title: 'aag', parent_id: 27},
{id: 30, title: 'aah', parent_id: 24},
{id: 31, title: 'aaz', parent_id: 24},
]
new_arr = []
get_child = -> (item) do
find_result = arr.select { |x| x[:parent_id] == item[:id] }
if find_result.any?
arr = arr - find_result
new_arr += find_result
find_result.each do |x|
get_child.call(x)
end
end
end
get_child.call({id: 25, parent_id: 23})
puts new_arr
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question