I have the following array:
votes_array = [["2", "1"], ["2", "4"], ["4", "3"], ["3", "4"], ["1", "N"], ["3", "1"], ["1", "2"], ["4", "1"], ["0", "1"], ["0", "2"], ["1", "3"], ["1", "4"]]
And I want to create a new array (or hash) that stores the votes_array items by their first option so that the new array looks like this:
candidate_votes = [
{"id" => "0", "votes" => [["0", "1"],["0","2"]]},
{"id" => "1", "votes" => [["1", "N"],["1","2"],["1","3"],["1","4"]]},
etc,
etc]
The order of the votes within the 'votes' key is not important, just that all the votes get split into the relevant ids.
I've got it working with the following code:
first_preferences = votes_array.map(&:first)
valid_candidates = first_preferences.uniq
valid_candidates.each do |candidate|
these_votes = votes_array.find_all { |i| i[0] == candidate }
candidate_votes << {"id" => candidate, "votes" => these_votes}
end
But wondered if there's a more elegant, cleaner or Rubiyst way?