YoDK YoDK - 20 days ago 7
Ruby Question

Using .sort_by to sort a nested array

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.

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

Answer
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"]
  #   ]}]] 
Comments