Sorting a Multidimensional Array in Ruby

Sorting a two-dimensional array by second value

arr = [[:z,1], [:d,3], [:e,2]]
arr.sort {|a,b| a[1] <=> b[1]}
# => [[:z, 1], [:e, 2], [:d, 3]]

Or as user @Phrogz points out, if the inner arrays have exactly two elements each:

arr.sort_by{|x,y|y} # => [[:z, 1], [:e, 2], [:d, 3]]
arr.sort_by(&:last) # => [[:z, 1], [:e, 2], [:d, 3]]

How to sort a two-dimensional array (2d array) by date in ruby on rails?

You can sort 2d arrays with sort_by method: sort_by sorts in ascending order by default. If you want it to be in descending order, just reverse the result.

array.sort_by{ |a| a.first }.reverse

sorting a multidimensional array in ruby

Use this on your hash:

hash.values.max

If you only need the highest element, there is no need to sort it!

Ruby - Sort multidimensional array by first line

You can use Array#transpose and Enumerable#sort_by to handle this like so:

 arr = [ [ "A 1", "A 3", "A 2", "A 4" ],
[ 4, 5, 6, 7 ],
[ 2, 2, 2, 2 ],
[ 0.1, 0.2, 0.1, 0.2 ] ]

Array#transpose turns rows into columns:

arr.transpose
#=> [["A 1", 4, 2, 0.1],
# ["A 3", 5, 2, 0.2],
# ["A 2", 6, 2, 0.1],
# ["A 4", 7, 2, 0.2]]

Then we just need to sort by the first column values sort_by(&:first):

arr.transpose.sort_by(&:first)
#=> [["A 1", 4, 2, 0.1],
# ["A 2", 6, 2, 0.1],
# ["A 3", 5, 2, 0.2],
# ["A 4", 7, 2, 0.2]]

Then we just transpose back again:

arr.transpose.sort_by(&:first).transpose
#=> [["A 1", "A 2", "A 3", "A 4"],
# [4, 6, 5, 7],
# [2, 2, 2, 2],
# [0.1, 0.1, 0.2, 0.2]]

The same could be achieved by zipping the Arrays together like so: (but the former seems like a better choice)

arr.reduce(&:zip).sort_by {|a| a.flatten!.first}.transpose
#=> [["A 1", "A 2", "A 3", "A 4"],
# [4, 6, 5, 7],
# [2, 2, 2, 2],
# [0.1, 0.1, 0.2, 0.2]]

How to sort alphabetically within a multidimensional array?

If you want sort the array by the lastname (the first element of each sub array) you could do easily with this:

myArray.sort { |x,y| x[0] <=> y[0] }

myArray = [['Jones', 'Layla'], ['Smith', 'Gary'], ['Williams', 'Nick'], ['Brown', 'Kyle']]
=> [["Jones", "Layla"], ["Smith", "Gary"], ["Williams", "Nick"], ["Brown", "Kyle"]]
myArray.sort { |x,y| x[0] <=> y[0] }
=> [["Brown", "Kyle"], ["Jones", "Layla"], ["Smith", "Gary"], ["Williams", "Nick"]]

sort documentation here

Sorting a specific MultiDimensional Array in Ruby

Sortintg multi-dimensional array - that is array of arrays - in Ruby is no different than sorting array of any other object.

a.sort { |x,y| y[5] <=> x[5] }

or

a.sort! { |x,y| y[5] <=> x[5] }

where 5 is index o your date column.

Sorting a two-dimensional array with more than one criterion

matrix.sort_by {|e| [e[0], -e[1]]}

I think that's the simplest but according to the docs, it can be quite expensive when the keysets are simple.



Related Topics



Leave a reply



Submit