Sorting: Sort array based on multiple conditions in Ruby

后端 未结 3 1019
不思量自难忘°
不思量自难忘° 2021-02-01 05:09

I have a mulitdimensional array like so:

[
  [name, age, date, gender]
  [name, age, date, gender]
  [..]
]

I\'m wondering the best way to sort

3条回答
  •  隐瞒了意图╮
    2021-02-01 05:52

    As I understand it you want to order by age first, and then if more than one record has the same age, arrange that subset by name.


    This works for me

    people = [
          ["bob", 15, "male"], 
          ["alice", 25, "female"], 
          ["bob", 56, "male"], 
          ["dave", 45, "male"], 
          ["alice", 56, "female"], 
          ["adam", 15, "male"]
        ]
    
    people.sort{|a,b| (a[1] <=> b[1]) == 0 ? (a[0] <=> b[0]) : (a[1] <=> b[1]) }
    
    # The sorted array is
    
    [["adam", 15, "male"], 
     ["bob", 15, "male"], 
     ["alice", 25, "female"], 
     ["dave", 45, "male"], 
     ["alice", 56, "female"], 
     ["bob", 56, "male"]]
    

    What this is doing is comparing by age first, and if the age is the same (<=> returs 0) it comparing the name.

提交回复
热议问题