Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .sort_by to sort a nested array

Tags:

ruby

I have a nested array that I want to sort by a specific object, some advice would be very much appreciated.

In this example I'd like the output to return sorted by the dates that are nested.

arr =    [
           [
             {  
               "log"=>[
                 [
                   "2016-09-03T00:00:00-03:00",
                 ],
                 [
                   "2016-09-01T00:00:00-03:00",
                 ],
                 [
                   "2016-09-02T00:00:00-03:00",
                 ]
               ]
             }
           ]
         ]
like image 991
YoDK Avatar asked Nov 29 '25 05:11

YoDK


1 Answers

arr = [
        [
          {  
            "log"=>[
               ["2016-09-03T00:00:00-03:00"],
               ["2016-09-01T00:00:00-03:00"],
               ["2016-09-02T00:00:00-03:00"]
            ]
          }
        ]
      ]

To return a sorted array and not mutate arr:

[[{ "log"=>arr[0][0]["log"].sort_by(&:first) }]]
  #=> [[{"log"=>[
  #       ["2016-09-01T00:00:00-03:00"],
  #       ["2016-09-02T00:00:00-03:00"],
  #       ["2016-09-03T00:00:00-03:00"]
  #   ]}]] 

To sort in place:

arr[0][0]["log"] = arr[0][0]["log"].sort_by(&:first)
  #=> [["2016-09-01T00:00:00-03:00"],
  #    ["2016-09-02T00:00:00-03:00"],
  #    ["2016-09-03T00:00:00-03:00"]] 
arr
  #=> [[{"log"=>[
  #       ["2016-09-01T00:00:00-03:00"],
  #       ["2016-09-02T00:00:00-03:00"],
  #       ["2016-09-03T00:00:00-03:00"]
  #   ]}]] 
like image 132
Cary Swoveland Avatar answered Nov 30 '25 18:11

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!