Skip to content

Instantly share code, notes, and snippets.

@umar-webonise
Created August 4, 2015 09:47
Show Gist options
  • Save umar-webonise/c6f0793399da9de235f0 to your computer and use it in GitHub Desktop.
Save umar-webonise/c6f0793399da9de235f0 to your computer and use it in GitHub Desktop.
Tree Algo
sections = Section.includes(:questions).as_json(
only: [:_id, :id, :name, :description, :template_id, :section_id],
include: {
questions: {
only: [:_id, :description, :helptext]
}
}
)
section_hash = sections.index_by { |node| node['_id'].to_s }
section_hash.each_value do |node|
section_id = node['section_id'].to_s
next if section_id.blank?
children = section_hash[section_id]['sections'] ||= []
children << node
end
result = []
section_hash.each_value do |value|
result.push(value) if value['template_id'].present?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment