Ruby Multidimensional Array - Remove duplicate in first position, add number in second position -
for array:
items = [[60, 3], [60, 3], [276, 2], [276, 2], [48, 2], [207, 2], [46, 2], [60, 2], [280, 2], [207, 1], [48, 1], [112, 1], [60, 1], [207, 1], [112, 1], [276, 1], [48, 1], [276, 1], [48, 1], [276, 1], [276, 1], [278, 1], [46, 1], [48, 1], [279, 1], [207, 1]]
i want combine common numbers in first positions of each sub-array, , add numbers in second positions together.
for instance, you'll see first 4 sub-arrays here are: [60, 3], [60, 3], [276, 2], [276, 2]
this become: [60,6], [276,4]
, on.
try this
items. group_by {|i| i[0]}. map{|key, value| [key,value.inject(0){|sum, x| sum + x[1]}]}
firstly, use group_by create hash keys first element of each array. have
{ 60=>[[60, 3], [60, 3], [60, 2], [60, 1]], 276=>[[276, 2], [276, 2], [276, 1], [276, 1], [276, 1], [276, 1]], 48=>[[48, 2], [48, 1], [48, 1], [48, 1], [48, 1]], 207=>[[207, 2], [207, 1], [207, 1], [207, 1]], 46=>[[46, 2], [46, 1]], 280=>[[280, 2]], 112=>[[112, 1], [112, 1]], 278=>[[278, 1]], 279=>[[279, 1]] }
then create desired result, using map method loop hash. calculate total value each key, using inject method sum second value of each array
[[60, 3], [60, 3], [60, 2], [60, 1]].inject(0) {|sum, x| sum + x[1]} #value 9
Comments
Post a Comment