Skip to content

Instantly share code, notes, and snippets.

@robertsosinski
Created March 8, 2012 21:08
Show Gist options
  • Save robertsosinski/2003463 to your computer and use it in GitHub Desktop.
Save robertsosinski/2003463 to your computer and use it in GitHub Desktop.
Use reduce to build a hierarchical tree of items (with help of spikegrobstein)
categories = [
{:id => 3, :name => "MLB", :parent => 2},
{:id => 2, :name => "Baseball", :parent => 1},
{:id => 1, :name => "Sports", :parent => nil}
]
categories.reverse.reduce(nil) do |memo, category|
memo = {
:id => category[:id],
:name => category[:name],
:parent => memo
}
memo
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment