Using Ruby .map Method To Combine Arrays With Unique Nested Values -


i'm trying use map function combine array of arrays array of arrays eliminate unique value in arr[0][0] pull arr[0][1] , group corresponding unique value.

arr = [[a, 1], [a, 2], [b,3], [b, 4]] => [[a, [1, 2]], [b, [3,4]]] 

i'm sure pretty basic i'm rather new coding in general. thank help.

try this:

arr = [[:a, 1], [:a, 2], [:b, 3], [:b, 4]]  arr.group_by(&:first).map { |k, v| [k, v.map(&:last)] } #=> [[:a, [1, 2]], [:b, [3, 4]]] 

depending on goal is, might want turn result hash:

hash[arr.group_by(&:first).map { |k, v| [k, v.map(&:last)] }] #=> {:a=>[1, 2], :b=>[3, 4]} 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -