Sort array of hashes based on two properties

浪子不回头ぞ 提交于 2021-01-29 07:17:06

问题


I have an array of hashes which I'd like to sort by one of the values. However, if two hashes have the same value if like to sort them on a second (backup) value.

In the example below I'd like to sort the hashes based of the value of "a". If two elements have the same value for "a" I'd like to sort by the value of "b" as a backup.

# Notice the first and last hashes have the same value for "a"
hashes = [
  {a: 2, b: 7},
  {a: 1, b: 0},
  {a: 9, b: 6},
  {a: 2, b: 8}
]

Output

{a: 1, b: 0},
{a: 2, b: 7},
{a: 2, b: 8},
{a: 9, b: 6}

回答1:


I think this is pretty easy with using of #sort_by with #values_at

hashes.sort_by { |e| e.values_at(:a, :b) }
=> [{:a=>1, :b=>0},
    {:a=>2, :b=>7},
    {:a=>2, :b=>8},
    {:a=>9, :b=>6}]

it also might be expanded, for example, you have array of hashes with 3 keys:

hashes = [
  {a: 2, b: 7, c: 8},
  {a: 1, b: 0, c: 5},
  {a: 9, b: 6, c: 6},
  {a: 2, b: 7, c: 3}
]

then:

hashes.sort_by { |e| e.values_at(:a, :b, :c) }

=> [{:a=>1, :b=>0, :c=>5},
    {:a=>2, :b=>7, :c=>3},
    {:a=>2, :b=>7, :c=>8},
    {:a=>9, :b=>6, :c=>6}]



回答2:


Try the below:

hashes.sort { |hash1, hash2| [hash1[:a], hash1[:b]] <=> [hash2[:a], hash2[:b]]}


来源:https://stackoverflow.com/questions/63987833/sort-array-of-hashes-based-on-two-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!