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]]?
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.
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.
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.
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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With