Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order Alphabetically and Display By Group

I'm trying to display a list of titles from my database in alphabetical order and also in blocks.

I want to output the letter and then include all titles that start with that letter. For example:

  • A
    • Apple
    • anotherthing
  • B
    • Bob

I know that I can order my results using .order('title'), but I'm not sure what the best way to write the display code is?

like image 814
spyderman4g63 Avatar asked Feb 20 '23 21:02

spyderman4g63


1 Answers

titles.group_by {|word| word[0].upcase }

So, then if:

titles = ['Apple', 'anothersomething', 'Bob']

Then:

grouped_titles = titles.group_by {|word| word[0].upcase }
 => {"A"=>["Apple", "anothersomething"], "B"=>["Bob"]} 

In order to be certain about the ordering, you can sort the resulting Hash, which converts it into an array:

grouped_titles = grouped_titles.sort_by{|k, v| k}
 => [["A", ["Apple", "anothersomething"]], ["B", ["Bob"]]] 

Then you can iterate over the resulting array.

<% grouped_titles.each do |initial_letter, titles| %>
 -display stuff here-
<% end %>

Note that this is grouping in Ruby, rather than in the database (which would be done by using a .group method on the relation), but if you were already displaying all the data in the page, this method should be fine.

like image 100
MrTheWalrus Avatar answered Mar 06 '23 04:03

MrTheWalrus