I have this nested array:
[[1, 2, 3],
[1, 3, 6],
[1, 4, 12],
[1, 5, 5],
[1, 2, 3],
[1, 8, 7],
[2, 3, 3],
[2, 4, 9],
[2, 5, 2],
[2, 8, 4],
[3, 4, 6],
[3, 8, 1],
[5, 8, 2],
[2, 8, 4],
[7, 8, 9]]
and I am trying to find a succinct but readable way of:
I've unsuccessfully played around with various methods such as #max
, #max_by
, #group_by
, #with_index
but I'm now at the stage where I could just do with some enlightenment from a more capable brain and programmer then me.
Finding the nested array with the max value on the last element:
input = [[1, 2, 3], [1, 3, 6], [1, 4, 12], [1, 5, 5], [1, 2, 3], [1, 8, 7], [2, 3, 3], [2, 4, 9], [2, 5, 2], [2, 8, 4], [3, 4, 6], [3, 8, 1], [5, 8, 2], [2, 8, 4], [7, 8, 9]]
input.max_by(&:last)
#=> [1, 4, 12]
And to only return its first two values:
input.max_by(&:last).take(2)
#=> [1, 4]