Find most common string in an array

前端 未结 6 1918
说谎
说谎 2020-12-24 07:42

I have this array, for example (the size is variable):

   x = [\"1.111\", \"1.122\", \"1.250\", \"1.111\"]

and I need to find the most comm

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 08:35

    It will return most popular value in array

    x.group_by{|a| a }.sort_by{|a,b| b.size<=>a.size}.first[0]
    

    IE:

    x = ["1.111", "1.122", "1.250", "1.111"]
    # Most popular
    x.group_by{|a| a }.sort_by{|a,b| b.size<=>a.size}.first[0]
    #=> "1.111
    # How many times
    x.group_by{|a| a }.sort_by{|a,b| b.size<=>a.size}.first[1].size
    #=> 2
    

提交回复
热议问题