Clarkekee
Clarkekee

Reputation: 1

How do I group arrays by the first 2 values and sum their corresponding number in ruby?

I came across this question How to group and sum arrays in Ruby? and was wondering how to apply it to my current problem at hand.

I have a multidimensional array with values as follows:

[[0,0,5],
[0,0,10],
[1,0,4],
[1,0,8],
[1,2,5],
[1,2,6]]

and I need to sum the 3rd value in each sub-array according to the 1st and 2nd values to get this output:

[[0,0,15], [1,0,12], [1,2,11]]

Any idea how to get this done? Thanks for the help!

Upvotes: 0

Views: 58

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

input.group_by { |e| e.take(2) }
     .map { |k, vals| [*k, vals.map(&:last).reduce(:+)] }
#⇒ [[0, 0, 15], [1, 0, 12], [1, 2, 11]]

or

input.group_by { |e| e.take(2) }
     .map { |k, vals| [k, vals.map(&:last).reduce(:+)] }.to_h
#⇒ {[0, 0]=>15, [1, 0]=>12, [1, 2]=>11}

Used here:

Upvotes: 2

XQY
XQY

Reputation: 562

An approach using group_by

inputs.group_by{|x| [x[0], x[1]]}.map{|k, v| [*k, v.map{|z| z[2]}.inject(:+)] }

Upvotes: 1

Related Questions