Zhen Liang Low
Zhen Liang Low

Reputation: 21

Sorting of 2D Array by its amount of in the inner elements

How do I sort a 2D array by the length of its inner elements? The number of inner elements is not the same.

Example:

a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]

After sorting, the array will become:

#=> [[4, 5, 6, 7], [2, 3], [8, 9], [1]]

Upvotes: 1

Views: 675

Answers (2)

Roko
Roko

Reputation: 1325

Try this:

a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]
a.sort { |x, y| y.size <=> x.size }
#=> [[4, 5, 6, 7], [2, 3], [8, 9], [1]]

Upvotes: 2

Alex Pan
Alex Pan

Reputation: 4571

This solution works:

a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]
a.sort_by! { |array| -array.length }
#=> [[4, 5, 6, 7], [8, 9], [2, 3], [1]]

I am using the sort_by method and sort by length from largest to smallest.

This solution is more readable and works as well, but it is a bit slower:

a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]
a.sort_by(&:length).reverse!
#=> [[4, 5, 6, 7], [8, 9], [2, 3], [1]]

I am using the sort_by method using length, which will sort the array from smallest to largest by length. Then I use the reverse! method it to have it in order from largest to smallest.

Upvotes: 3

Related Questions