8

Suppose I have

an_array = [[2, 3], [1, 4], [1, 3], [2, 1], [1, 2]]

I want to sort this array by the first value of each inner array, and then by the second (so the sorted array should look like this: [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3]])

What's the most readable way to do this?

3 Answers 3

13

This is the default behavior for sorting arrays (see the Array#<=> method definition for proof). You should just be able to do:

 an_array.sort
Sign up to request clarification or add additional context in comments.

Comments

9

If you want some non-default behaviour, investigate sort_by (ruby 1.8.7+)

e.g. sort by the second element then by the first

a.sort_by {|e| [e[1], e[0]]}  # => [[2, 1], [1, 2], [1, 3], [2, 3], [1, 4]]

or sort by the first element ascending and then the second element descending

a.sort_by {|e| [e[0], -e[1]]}  # => [[1, 4], [1, 3], [1, 2], [2, 3], [2, 1]]

Comments

1

an_array.sort

Comments

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.