i'm working multiple arrays each 1 string , many integers. have managed set duplicates in nested arrays want combine them. loop on parent array outputs this:
[["word", 1, 1, 3, 4], ["word", 2, 1, 3, 4]] and example:
[["without", 1, 1, 3, 4], ["without", 2, 1, 3, 4], ["without", 3, 1, 0, 0]] i want function combine these 1 array , sum integers. first example above become:
["word", 3, 2, 6, 8] i have tried many different techniques inject , reduce. latest attempt isn't elegant:
# data set of array def inject_array(data) clicks = 0 imps = 0 cost = 0 converted_clicks = 0 data.each |i| clicks += i[1] i[1] = clicks imps += i[2] i[2] = imps cost += i[3] i[3] = cost converted_clicks += i[4] i[4] = converted_clicks end it's getting bit messy, there cleaner way?
assuming arrays same length, can use array#transpose transpose array of arrays row-based column-based arrays:
[["word", 1, 1, 3, 4], ["word", 2, 1, 3, 4]].transpose => [["word", "word"], [1, 2], [1, 1], [3, 3], [4, 4]] from there, it's trivial enough sum numbers in each:
[["word", 1, 1, 3, 4], ["word", 2, 1, 3, 4]].transpose.map.with_index |e, i| == 0 ? e.first : e.inject(:+) end # => ["word", 3, 2, 6, 8]
Comments
Post a Comment