Merge nested array of hashes in ruby - ruby-on-rails

In sample code nameA and nameB missing few dates when comparing with common_count.
So, the expected output hash must be present missing dates with value will be zero
Thank you in advance.
"common_count"=>[
{20190704=>0}, {20190705=>0}, {20190706=>0}, {20190707=>0},
{20190708=>0}, {20190709=>0}, {20190710=>0}, {20190711=>0}
]
}
{
"nameA"=>[
{20190704=>10} {20190706=>50}, {20190707=>10},
{20190708=>0}, {20190709=>10}, {20190710=>0}, {20190711=>40}
],
"nameB"=>[
{20190704=>30}, {20190707=>20},
{20190708=>3}, {20190709=>5}, {20190710=>0}, {20190711=>20}
], ..... etc
}
"nameA"=>[
{20190704=>10}, {20190705=>0}, {20190706=>50}, {20190707=>10},
{20190708=>0}, {20190709=>10}, {20190710=>0}, {20190711=>40}
],
"nameB"=>[
{20190704=>30},{20190705=>0}, {20190706=>0} {20190707=>20},
{20190708=>3}, {20190709=>5}, {20190710=>0}, {20190711=>20}
],...etc
}

You could simply:
entries = {
"common_count"=>[
{"20190704"=>0}, {"20190705"=>0}, {"20190706"=>0}, {"20190707"=>0},
{"20190708"=>0}, {"20190709"=>0}, {"20190710"=>0}, {"20190711"=>0}
],
"nameA"=>[
{"20190704"=>10}, {"20190706"=>50}, {"20190707"=>10},
{"20190708"=>0}, {"20190709"=>10}, {"20190710"=>0}, {"20190711"=>40}
],
"nameB"=>[
{"20190704"=>30}, {"20190707"=>20},
{"20190708"=>3}, {"20190709"=>5}, {"20190710"=>0}, {"20190711"=>20}
]
}
default = entries.delete("common_count")
default_map = default.inject(:merge)
merged_entries = entries.map do |nameKey, value|
value_map = value.inject(:merge)
merged_value_map = default_map.merge(value_map)
merged_value = merged_value_map.map { |k, v| {k => v} }
{nameKey => merged_value}
end.inject(:merge)
Notice that I had to convert an array of hashes to a single hash in order to merge the hashes' contents. Then I reverted the hash result to an array of hashes.

If you have input like below,
common_count = [{"20190704"=>0}, {"20190705"=>0}, {"20190706"=>0}, {"20190707"=>0}, {"20190708"=>0}, {"20190709"=>0}, {"20190710"=>0}, {"20190711"=>0}]
nameA = [{"20190704"=>10}, {"20190706"=>50}, {"20190707"=>10}, {"20190708"=>0}, {"20190709"=>10}, {"20190710"=>0}, {"20190711"=>40}]
nameB = [{"20190704"=>30}, {"20190707"=>20}, {"20190708"=>3}, {"20190709"=>5}, {"20190710"=>0}, {"20190711"=>20}]
You can run following to add missing keys from common_count,
[nameA, nameB].each do |arr|
(common_count.map(&:keys).flatten - arr.map(&:keys).flatten).each do |missing|
arr.push({missing => 0})
end
end

Related

Find index of array in multidimensional array by string value

I need the index of an array in a multidimensional array if it contains a unique string.
array:
[
{:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
{:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
{:id=>16, :name=>"Navy", :hex_value=>"285974"}
]
If hex_value of 'FFF600' exists, return the arrays position, which in this case would be 1.
This is where I am at, but it's returning [].
index = array.each_index.select{|i| array[i] == '#FFF600'}
That's returning nil, because there's no element i (index) in the array with value #FFF600 (nor FFF600), you need to access to the hex_value key value:
p [
{:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
{:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
{:id=>16, :name=>"Navy", :hex_value=>"285974"}
].yield_self { |this| this.each_index.select { |index| this[index][:hex_value] == 'FFF600' } }
# [1]
Giving you [1], because of using select, if you want just the first occurrence, you can use find instead.
I'm using yield_self there, to avoid assigning the array to a variable. Which is equivalent to:
array = [
{:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
{:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
{:id=>16, :name=>"Navy", :hex_value=>"285974"}
]
p array.each_index.select { |index| array[index][:hex_value] == 'FFF600' }
# [1]
Being Ruby, you can use the method for that: Enumerable#find_index
p [
{:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
{:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
{:id=>16, :name=>"Navy", :hex_value=>"285974"}
].find_index { |hash| hash[:hex_value] == 'FFF600' }
# 1

Get first element of nested array for hash key

Supposing I have an array that looks like:
[
[["str1"],["val1"],["val2"]],
[["str2"], ["val1"], ["val2"], ["val3"]]
]
Is there a way for me to get a Hash that looks like:
{
"str1" => [["val1"],["val2"]],
"str2" => [["val1"],["val2"],["val3"]]
}
a.map { |a| [a.first.first, a.drop(1)] }.to_h
# or
a.each_with_object({}) {|a, h| h[a.first.first] = a.drop(1) }
#=> {
# "str1"=>[["val1"], ["val2"]],
# "str2"=>[["val1"], ["val2"], ["val3"]]
# }
If you do not want to have each element in a separate array:
Hash[a.map(&:flatten).map { |a| [a.first, a.drop(1)] }]
#=> {"str1"=>["val1", "val2"], "str2"=>["val1", "val2", "val3"]}
If your array is arr, you could write the following.
Marshal.load(Marshal.dump(arr)).map { |a| [a.shift.first, a.map(&:first)] }.to_h
#=> {"str1"=>["val1", "val2"],
# "str2"=>["val1", "val2", "val3"]}
A slight variation would be:
Marshal.load(Marshal.dump(arr)).map { |a| [a.shift.first, a] }.to_h
#=> {"str1"=>["val1", "val2"],
# "str2"=>["val1", "val2", "val3"]}
Note: We're using the Marshal class to make an exact copy of arr to avoid modifying the original array. Object#dup or Object#clone won't work here.
arr = [
[["str1"],["val1"],["val2"]],
[["str2"], ["val1"], ["val2"], ["val3"]]
]
arr.each_with_object({}) { |((k), *values), h| h[k]=values }
#=> {"str1"=>[["val1"], ["val2"]], "str2"=>[["val1"], ["val2"], ["val3"]]}
This illustrates how Ruby's use of parallel assignment for determining the values of block variables can be used to advantage.

Merge multidimensional array of hash based on hash key and value in ruby

I have one array and i want to match value of id key with other array of hash in multidimensional array,
input = [
[ {"id"=>"1","name"=>"a"},
{"id"=>"2","name"=>"b"},
{"id"=>"3","name"=>"c"},
{"id"=>"4","name"=>"d"},
{"id"=>"5","name"=>"e"},
{"id"=>"6","name"=>"f"}
],
[ {"id"=>"3","hoby"=>"AA"},
{"id"=>"3","hoby"=>"BB"},
{"id"=>"1","hoby"=>"CC"},
{"id"=>"1","hoby"=>"DD"},
{"id"=>"4","hoby"=>"EE"}
],
[ {"id"=>"1","language"=>"A"},
{"id"=>"1","language"=>"B"},
{"id"=>"2","language"=>"B"},
{"id"=>"2","language"=>"C"},
{"id"=>"6","language"=>"D"}
]
]
I need array output like,
output = [
{"id"=>"1","name"=>"a","id"=>"1","hoby"=>"CC","id"=>"1","language"=>"A","id"=>"1","language"=>"B"},
{"id"=>"2","name"=>"b","id"=>"2","language"=>"B"},
{"id"=>"3","name"=>"c","id"=>"3","hoby"=>"AA","id"=>"3","hoby"=>"BB"},
{"id"=>"4","name"=>"d","id"=>"4","hoby"=>"EE"},
{"id"=>"5","name"=>"e"},
{"id"=>"6","name"=>"f","id"=>"6","language"=>"D"}
]
I have wrote code for this,
len = input.length - 1
output = []
input[0].each do |value,index|
for i in 1..len
input[i].each do |j|
if value["id"] == j["id"]
output << value.merge(j)
end
end
end
end
But i am getting wrong output array.There might be any number of sub array in multidimensional array.
Thank,
First of all - it is impossible to have two elements in a hash with the same key. When assigning the value to some key will make the next assignment of the same key with new value override the previous one.
Let's consider the example:
hash = {}
hash["id"] = 1
hash["id"] = 3
hash["id"] = 5
What output for hash["id"] would you expect? 1, 3, 5 or maybe [1, 3, 5]? The way the Hash in ruby works it will output 5, because this is the last assignment to unique key.
Having said that, it is impossible to store multiple occurrences in your hash, but you can try processing it with something like:
input.flatten
.group_by { |h| h["id"] }
.map do |k, a|
a.each_with_object({}) { |in_h, out_h| out_h.merge!(in_h) }
end
Which will result with hash like:
[{"id"=>"1", "name"=>"a", "hoby"=>"DD", "language"=>"B"},
{"id"=>"2", "name"=>"b", "language"=>"C"},
{"id"=>"3", "name"=>"c", "hoby"=>"BB"},
{"id"=>"4", "name"=>"d", "hoby"=>"EE"},
{"id"=>"5", "name"=>"e"},
{"id"=>"6", "name"=>"f", "language"=>"D"}]
Well, it is not the hash as you would expect, but at least it might put you in some direction.
Hope that helps!
maybe this can help you.
input = [
[
{"id"=>"1","name"=>"a"},
{"id"=>"2","name"=>"b"},
{"id"=>"3","name"=>"c"},
{"id"=>"4","name"=>"d"},
{"id"=>"5","name"=>"e"},
{"id"=>"6","name"=>"f"}
],
[
{"id"=>"3","hoby"=>"AA"},
{"id"=>"3","hoby"=>"BB"},
{"id"=>"1","hoby"=>"CC"},
{"id"=>"1","hoby"=>"DD"},
{"id"=>"4","hoby"=>"EE"}
],
[
{"id"=>"1","language"=>"A"},
{"id"=>"1","language"=>"B"},
{"id"=>"2","language"=>"B"},
{"id"=>"2","language"=>"C"},
{"id"=>"6","language"=>"D"}
]
]
This way you can make your "sort" results.
output = {}
input.flatten.each do |h|
output[h["id"]] = {} unless output[h["id"]]
output[h["id"]].merge!(h)
end
output.values
# => [
# => {"id"=>"1", "name"=>"a", "hoby"=>"DD", "language"=>"B"},
# => {"id"=>"2", "name"=>"b", "language"=>"C"},
# => {"id"=>"3", "name"=>"c", "hoby"=>"BB"},
# => {"id"=>"4", "name"=>"d", "hoby"=>"EE"},
# => {"id"=>"5", "name"=>"e"},
# => {"id"=>"6", "name"=>"f", "language"=>"D"}
# => ]
But the better way is use Hash in input. You can define input like hash and "id" like key so if you generate the data, you dont have problem to sort it.
Someting like this
{
"1" => {"name" => "a", "hoby" => "DD", "language" => "B"}
}

Ruby array of hash. group_by and modify in one line

I have an array of hashes, something like
[ {:type=>"Meat", :name=>"one"},
{:type=>"Meat", :name=>"two"},
{:type=>"Fruit", :name=>"four"} ]
and I want to convert it to this
{ "Meat" => ["one", "two"], "Fruit" => ["Four"]}
I tried group_by but then i got this
{ "Meat" => [{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}],
"Fruit" => [{:type=>"Fruit", :name=>"four"}] }
and then I can't modify it to leave just the name and not the full hash. I need to do this in one line because is for a grouped_options_for_select on a Rails form.
array.group_by{|h| h[:type]}.each{|_, v| v.replace(v.map{|h| h[:name]})}
# => {"Meat"=>["one", "two"], "Fruit"=>["four"]}
Following steenslag's suggestion:
array.group_by{|h| h[:type]}.each{|_, v| v.map!{|h| h[:name]}}
# => {"Meat"=>["one", "two"], "Fruit"=>["four"]}
In a single iteration over initial array:
arry.inject(Hash.new([])) { |h, a| h[a[:type]] += [a[:name]]; h }
Using ActiveSuport's Hash#transform_values:
array.group_by{ |h| h[:type] }.transform_values{ |hs| hs.map{ |h| h[:name] } }
#=> {"Meat"=>["one", "two"], "Fruit"=>["four"]}
array = [{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}, {:type=>"Fruit", :name=>"four"}]
array.inject({}) {|memo, value| (memo[value[:type]] ||= []) << value[:name]; memo}
I would do as below :
hsh =[{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}, {:type=>"Fruit", :name=>"four"}]
p Hash[hsh.group_by{|h| h[:type] }.map{|k,v| [k,v.map{|h|h[:name]}]}]
# >> {"Meat"=>["one", "two"], "Fruit"=>["four"]}
#ArupRakshit answer, slightly modified (the function has been added for sake of clarity in the final example):
def group(list, by, at)
list.group_by { |h| h[by] }.map { |k,v| [ k , v.map {|h| h[at]} ] }.to_h
end
sample =[
{:type=>"Meat", :name=>"one", :size=>"big" },
{:type=>"Meat", :name=>"two", :size=>"small" },
{:type=>"Fruit", :name=>"four", :size=>"small" }
]
group(sample, :type, :name) # => {"Meat"=>["one", "two"], "Fruit"=>["four"]}
group(sample, :size, :name) # => {"big"=>["one"], "small"=>["two", "four"]}
Please, notice that, although not mentioned in the question, you may want to preserve the original sample as it is. Some answers kept provision on this, others not as.
After grouping (list.group_by {...}) the part that does the transformation (without modifying the original sample's values) is:
.map { |k,v| [ k , v.map {|h| h[at]} ] }.to_h
Some hints:
iterating the pairs of the Hash of groups (first map), where
for each iteration, we receive |group_key, array] and return an Array of [group_key, new_array] (outer block),
and finally to_h transforms the Array of Arrays into the Hash (this [[gk1,arr1],[gk2,arr2]...] into this { gk1 => arr1, gk2 => arr2, ...})
There is one missing step not explained at step (2) above. new_array is made by v.map {|h| h[at]}, which justs casts the value at of each original Hash (h) element of the array (so we move from Array of Hashes to an Array of elements).
Hope that helps others to understand the example.

How can I replace a hash key with another key?

I have a condition that gets a hash.
hash = {"_id"=>"4de7140772f8be03da000018", .....}
Yet, I want to rename the key of that hash as follows.
hash = {"id"=>"4de7140772f8be03da000018", ......}
P.S. I don't know what keys are in the hash; they are random. Some keys are prefixed with an underscore that I would like to remove.
hash[:new_key] = hash.delete :old_key
rails Hash has standard method for it:
hash.transform_keys{ |key| key.to_s.upcase }
http://api.rubyonrails.org/classes/Hash.html#method-i-transform_keys
UPD: ruby 2.5 method
If all the keys are strings and all of them have the underscore prefix, then you can patch up the hash in place with this:
h.keys.each { |k| h[k[1, k.length - 1]] = h[k]; h.delete(k) }
The k[1, k.length - 1] bit grabs all of k except the first character. If you want a copy, then:
new_h = Hash[h.map { |k, v| [k[1, k.length - 1], v] }]
Or
new_h = h.inject({ }) { |x, (k,v)| x[k[1, k.length - 1]] = v; x }
You could also use sub if you don't like the k[] notation for extracting a substring:
h.keys.each { |k| h[k.sub(/\A_/, '')] = h[k]; h.delete(k) }
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
And, if only some of the keys have the underscore prefix:
h.keys.each do |k|
if(k[0,1] == '_')
h[k[1, k.length - 1]] = h[k]
h.delete(k)
end
end
Similar modifications can be done to all the other variants above but these two:
Hash[h.map { |k, v| [k.sub(/\A_/, ''), v] }]
h.inject({ }) { |x, (k,v)| x[k.sub(/\A_/, '')] = v; x }
should be okay with keys that don't have underscore prefixes without extra modifications.
you can do
hash.inject({}){|option, (k,v) | option["id"] = v if k == "_id"; option}
This should work for your case!
If we want to rename a specific key in hash then we can do it as follows:
Suppose my hash is my_hash = {'test' => 'ruby hash demo'}
Now I want to replace 'test' by 'message', then:
my_hash['message'] = my_hash.delete('test')
For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:
hash1 = { '_id' => 'random1' }
hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }
hash1.transform_keys { |key| key.delete_prefix('_') }
# => {"id"=>"random1"}
hash2.transform_keys { |key| key.delete_prefix('old_') }
# => {"first"=>"123456", "second"=>"234567"}
hash3.transform_keys { |key| key.delete_suffix('_com') }
# => {"first"=>"google.com", "second"=>"amazon.com"}
h.inject({}) { |m, (k,v)| m[k.sub(/^_/,'')] = v; m }
hash.each {|k,v| hash.delete(k) && hash[k[1..-1]]=v if k[0,1] == '_'}
I went overkill and came up with the following. My motivation behind this was to append to hash keys to avoid scope conflicts when merging together/flattening hashes.
Examples
Extend Hash Class
Adds rekey method to Hash instances.
# Adds additional methods to Hash
class ::Hash
# Changes the keys on a hash
# Takes a block that passes the current key
# Whatever the block returns becomes the new key
# If a hash is returned for the key it will merge the current hash
# with the returned hash from the block. This allows for nested rekeying.
def rekey
self.each_with_object({}) do |(key, value), previous|
new_key = yield(key, value)
if new_key.is_a?(Hash)
previous.merge!(new_key)
else
previous[new_key] = value
end
end
end
end
Prepend Example
my_feelings_about_icecreams = {
vanilla: 'Delicious',
chocolate: 'Too Chocolatey',
strawberry: 'It Is Alright...'
}
my_feelings_about_icecreams.rekey { |key| "#{key}_icecream".to_sym }
# => {:vanilla_icecream=>"Delicious", :chocolate_icecream=>"Too Chocolatey", :strawberry_icecream=>"It Is Alright..."}
Trim Example
{ _id: 1, ___something_: 'what?!' }.rekey do |key|
trimmed = key.to_s.tr('_', '')
trimmed.to_sym
end
# => {:id=>1, :something=>"what?!"}
Flattening and Appending a "Scope"
If you pass a hash back to rekey it will merge the hash which allows you to flatten collections. This allows us to add scope to our keys when flattening a hash to avoid overwriting a key upon merging.
people = {
bob: {
name: 'Bob',
toys: [
{ what: 'car', color: 'red' },
{ what: 'ball', color: 'blue' }
]
},
tom: {
name: 'Tom',
toys: [
{ what: 'house', color: 'blue; da ba dee da ba die' },
{ what: 'nerf gun', color: 'metallic' }
]
}
}
people.rekey do |person, person_info|
person_info.rekey do |key|
"#{person}_#{key}".to_sym
end
end
# =>
# {
# :bob_name=>"Bob",
# :bob_toys=>[
# {:what=>"car", :color=>"red"},
# {:what=>"ball", :color=>"blue"}
# ],
# :tom_name=>"Tom",
# :tom_toys=>[
# {:what=>"house", :color=>"blue; da ba dee da ba die"},
# {:what=>"nerf gun", :color=>"metallic"}
# ]
# }
Previous answers are good enough, but they might update original data.
In case if you don't want the original data to be affected, you can try my code.
newhash=hash.reject{|k| k=='_id'}.merge({id:hash['_id']})
First it will ignore the key '_id' then merge with the updated one.
Answering exactly what was asked:
hash = {"_id"=>"4de7140772f8be03da000018"}
hash.transform_keys { |key| key[1..] }
# => {"id"=>"4de7140772f8be03da000018"}
The method transform_keys exists in the Hash class since Ruby version 2.5.
https://blog.bigbinary.com/2018/01/09/ruby-2-5-adds-hash-transform_keys-method.html
If you had a hash inside a hash, something like
hash = {
"object" => {
"_id"=>"4de7140772f8be03da000018"
}
}
and if you wanted to change "_id" to something like"token"
you can use deep_transform_keys here and do it like so
hash.deep_transform_keys do |key|
key = "token" if key == "_id"
key
end
which results in
{
"object" => {
"token"=>"4de7140772f8be03da000018"
}
}
Even if you had a symbol key hash instead to start with, something like
hash = {
object: {
id: "4de7140772f8be03da000018"
}
}
you can combine all of these concepts to convert them into a string key hash
hash.deep_transform_keys do |key|
key = "token" if key == :id
key.to_s
end
If you only want to change only one key, there is a straightforward way to do it in Ruby 2.8+ using the transform_keys method. In this example, if you want to change _id to id, then you can:
hash.transform_keys({_id: :id})
Reference: https://bugs.ruby-lang.org/issues/16274

Resources