Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a two-dimensional array by second value

Tags:

Ok, say I have an array like so [[z,1], [d,3], [e,2]], how can I sort this array by the second element of each constituent array? So that my array would look like the following? [[z,1], [e,2], [d,3]]?

like image 716
Richard Stokes Avatar asked Aug 11 '11 22:08

Richard Stokes


People also ask

How do you sort a 2D array?

Example for 2D array sorting in Java to sort all elements of a 2D Array. As in the above program, the sort() method is used to iterate each element of a 2D array, and when the current element is greater than the next element, then swap the numbers. Finally, the print method displays all the elements of the 2D array.

How do you sort a two-dimensional array by column value?

To sort 2 dimensional array by column value with JavaScript, we can use the array sort method. const arr = [ [12, "AAA"], [12, "BBB"], [12, "CCC"], [28, "DDD"], [18, "CCC"], [12, "DDD"], [18, "CCC"], [28, "DDD"], [28, "DDD"], [58, "BBB"], [68, "BBB"], [78, "BBB"], ]; const sortedArr = arr.

How do you sort a 2D array in descending order Python?

Sort the rows of a 2D array in descending order The code axis = 1 indicates that we'll be sorting the data in the axis-1 direction, and by using the negative sign in front of the array name and the function name, the code will sort the rows in descending order.


2 Answers

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]] 
like image 168
maerics Avatar answered Oct 12 '22 23:10

maerics


As user maerics answer it provides Ascending sorting.This answer is very useful for me thanks. For Descending sorting i use -

arr = [[:z,1], [:d,3], [:e,2]] arr.sort {|a,b| a[1] <=> b[1]}.reverse #=> [[:d, 3], [:e, 2], [:z, 1]] 
like image 22
Sandip Karanjekar Avatar answered Oct 12 '22 23:10

Sandip Karanjekar