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

前端 未结 2 825
星月不相逢
星月不相逢 2021-01-25 01:42

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,          


        
2条回答
  •  执笔经年
    2021-01-25 02:24

    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.

提交回复
热议问题