This is the array version of: Sum 2 hashes attributes with the same key
I have 2 arrays, for example:
a = [[1,10],[2,20],[3,30]]
b = [[1,50],[3,70]]
How can i sum each on the first value (if it exists) to get:
c = [[1,60],[2,20],[3,100]]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could do it thusly:
First you put the arrays together with
+since you don’t care aboutaandb, you just care about their elements. Then thegroup_bypartitions the combined array by the first element so that the inner arrays can easily be worked with. Then you just have to pull out the second (or last) elements of the inner arrays withv.map(&:last)and sum them withinject(:+).For example: