两级数组排序,其中一个第二级数组成员始终位于顶部

时间:2015-08-19 18:32:26

标签: ruby database sorting ruby-on-rails-4 activerecord

我有一个两级数组,每个元素都有一个类别和一个子类别,如下所示:

[[category1, subcategory1], [category1, subcategory2], [category2, subcategory2], [category3, subcategory3]]...

我在下拉列表中使用它,将显示如下列表:

category1
  general
  subcategory1
  subcategory2
category2
  general
  subcategory1
  subcategory2
  subcategory3

基本上,我需要让'general'子类别始终显示在子类别列表的顶部,如果它存在,则按字母顺序排列。我该怎么编码?

使用ActiveRecord,对数组本身进行字母排序相对容易: ModelName.pluck(:category, :subcategory).sort

但这不会将子类别“一般”放在首位。它将按字母顺序排列。我更喜欢使用rails解决方案,但是在指向正确方向的任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

categorization = ModelName.pluck(:category, :subcategory)
    # => [["category1", "subcategory1"],
    #     ["category1", "subcategory2"],
    #     ["category1", "general"],
    #     ["category2", "general"],
    #     ["category2", "subcategory2"],
    #     ["category3", "subcategory3"],
    #     ["category3", "general"]]


categorization.sort_by! do |category, subcategory|
  subcategory == 'general' ? [category, ''] : [category, subcategory]
end
    # => [["category1", "general"],
    #     ["category1", "subcategory1"],
    #     ["category1", "subcategory2"],
    #     ["category2", "general"],
    #     ["category2", "subcategory2"],
    #     ["category3", "general"],
    #     ["category3", "subcategory3"]]

答案 1 :(得分:0)

如果我是你,我会格式化数据库查询结果,使其看起来像

/portfolio

如果{ "category1" => ["general", "subcategory1", "subcategory2", ...], "category2" => ["general", "subcategory1", "subcategory2", ...], ... } 存储在数据库中,则

"general"

如果ModelName.pluck(:category, :subcategory).sort.reduce(Hash.new{['general']}) do |hash, model| hash[model[0]] <<= model[1] end 位于数据库中,那么只需从每个数组中删除"general",然后取消它:

"general"