3

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",
                 ]
               ]
             }
           ]
         ]
1
  • 1
    When you give an example it is helpful to assign a variable to each input object (e.g., arr = [[{ "log"=>....). That way readers can refer to the variable in answers and comments without having to define it. Commented Nov 15, 2016 at 0:47

1 Answer 1

3
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"]
  #   ]}]] 
Sign up to request clarification or add additional context in comments.

2 Comments

This is only going to work on that single array element. If either of the two outer arrays have multiple elements, it's only going to handle the first one.
@Jim, yes, that's true, and something I mulled in preparing my answer. The problem is that to deal with a more general case additional specification would be required. Suppose, for example, arr = [[{ "log"=>[ ["2016-09-03T00:00:00-03:00"], ["2016-09-01T00:00:00-03:00"]] }], [{ "log"=>[ ["2015-08-03T00:00:00-03:00"], ["2015-08-01T00:00:00-03:00"]] }]]. In this case it's not clear what is wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.