[[1, 20],[2,30],[1,5],[4,5]]
In ruby how does one go through this array and add the second element if the first is the same with and output such as:
[[1, 25],[2,30],[4,5]]
[[1, 20],[2,30],[1,5],[4,5]]
In ruby how does one go through this array and add the second element if the first is the same with and output such as:
[[1, 25],[2,30],[4,5]]
A solution in Ruby:
L = [[1, 20],[2,30],[1,5],[4,5]]
d = {}
L.each{|k,v| d[k] = (d[k]||0) + v}
A solution in Python:
L = [[1, 20],[2,30],[1,5],[4,5]]
d = {}
for k,v in L:
d[k] = d.get(k,0) + v
You can do this (warning, the output is a bit garbled, you may want to convert to array):
myArray = [[1, 20],[2,30],[1,5],[4,5]]
outputHash = {}
myArray.each do |values|
outputHash[values[0]] = outputHash[values[0]].to_i + values[1]
end
puts outputHash
If order isn't important, inserting the pairs into a hash, adding if the key already exists, and then flattening the hash back into an array is a neat way. In irb:
>> a = [[1, 20],[2,30],[1,5],[4,5]]
=> [[1, 20], [2, 30], [1, 5], [4, 5]]
>> a.inject(Hash.new(0)) { |h, p| h[p[0]] += p[1]; h }.to_a
=> [[1, 25], [2, 30], [4, 5]]