sorting 2d array with nil value
-
14-11-2019 - |
Question
I have an array like this
a=[["address", "US"], ["company", "apple"], ["CEO", ""], ["Website", ""]]
I need the first values like ["address", "company", "CEO","Website"] so what i did was
a.transpose
I got
[["address", "company", "CEO", "Website"], ["US", "apple", "", ""]]
Now I need to sort the first array.. and its corresponding value when I do
[["address", "company", "CEO", "Website"], ["US", "apple", "", ""]].sort
I get
[["US", "apple", "", ""], ["address", "company", "CEO", "Website"]]
But what I want is
[["address", "CEO", "company", "Website"], ["US", "", "apple", "" ]
If any body could help that'd be gr8!
Solution
You can sort it like that:
a.sort_by { |e| e[0].downcase } .transpose
This first sorts the array with your custom criteria, and after that transposes the result, as you need it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow