1

given this array:

[ ["a", ["example1"]], ["a", ["example2"]], ["b", ["example3"]] ]

would like to merge each array with the same 'beginning'

result should be:

[ ["a", ["example1"], ["example2"]], ["b", ["example3"]] ]

i tried different points from http://www.ruby-doc.org/core-2.2.0/Array.html so far, but i dont get the correct condition to match the elements against each other.

2 Answers 2

2

This can be done using the built in functions group_by,map and flatten

x = [ ["a", ["example1"]], ["a", ["example2"]], ["b", ["example3"]] ]

p x.group_by(&:first).map{|x,y|[x,y.map(&:last)].flatten(1)} #=> ["a", ["example1"], ["example2"], ["b", ["example3"]]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, +vote for solution without hash type casting
Thank, but as a and b seems to be some kind of keys I would, if I could, try to store the data in a hash. But I do not, of course, know the nature of your data so I will no tell you what is best for you.
more easier code:x.group_by(&:first).map{|x,y|[x,*y.map(&:last)]}
0

I'd do :

array = [ ["a", ["example1"]], ["a", ["example2"]], ["b", ["example3"]] ]

output = array.each_with_object(Hash.new { |h,k| h[k] = [] }) do |in_ary, hash|
  hash[in_ary.first].concat(in_ary[1..-1])
end.map { |k, v| [k, *v] }
output # => [["a", ["example1"], ["example2"]], ["b", ["example3"]]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.