O
O
Ord EO2021-09-23 00:49:18
ruby
Ord EO, 2021-09-23 00:49:18

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 idparent 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},
]

How to write a method that will receive some element of the array as input, and return all its descendants as output? Example, I want to get all descendants of this element: {id: 24, parent_id: 23}. The method should return

[
  {id: 30, title: 'aah',  parent_id: 24},
  {id: 31, title: 'aaz', parent_id: 24},
]

Or, for example, I want to get the descendants of this element: {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

1 answer(s)
N
N. Bekseitov, 2021-09-23
@nbekseitov

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

Written in haste, edit somehow to suit your method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question