I have an array of arrays, containing aggregated data on total number of clients, total number of orders, total value of orders and location.
current_clients => [
[293, 2846, 28365.00, "Glasgow"],
[958, 8174, 85551.50, "Edinburgh"],
[177, 982, 10783.75, "Inverness"]
]
I have a separate array of hashes that contains data (from another source) which shares the same list of locations, with a count of the number of clients in our target market for that location.
prospective_clients => [
{location: "Edinburgh", count: 2433},
{location: "Glasgow", count: 1076},
{location: "Inverness", count: 524}
]
I need to combine them into a new array of arrays (or append the values of the array of hashes into the existing array of arrays) so that I can output that data into a report to show account managers their market penetration for each location. For that, I’ll need to loop through the arrays and match them on the location value, as the locations won’t necessarily always be in the same order within the arrays.
market_penetration => [
[293, 2846, 28365.00, "Glasgow", 1076],
[958, 8174, 85551.50, "Edinburgh", 2433],
[177, 982, 10783.75, "Inverness", 524]
]
I know how to get that market penetration data into a table once I’ve got it, but I just can’t work out how to combine or append the two. If it makes a difference/makes life easier, it is possible to get the prospective_clients list as another array of arrays, rather than an array of hashes.
I’ve only been working with Ruby on Rails for a couple of months, and all the textbooks and online courses I’ve done just deal with simplified examples either working with arrays or working with hashes; nowhere seems to cover real life application of dealing with more complex arrays of arrays and arrays of hashes, never mind trying to combine them... thanks in advance for any advice/solutions you can share.
You can generate a hash to easily look up the client count using each_with_object
. You can then map over the current_clients
array and add the client count.
prospective_clients_hash = prospective_clients.each_with_object({}) do |client, acc|
acc[client[:location]] = client[:count]
end
#=> {"Edinburgh"=>2433, "Glasgow"=>1076, "Inverness"=>524}
market_penetration = current_clients.map do |client|
location = client[3]
[*client, prospective_clients_hash[location]] # * is the splat operator
end
#=> [[293, 2846, 28365.0, "Glasgow", 1076], [958, 8174, 85551.5, "Edinburgh", 2433], [177, 982, 10783.75, "Inverness", 524]]