0

我正在尝试使用表格制作页面,其中内容是来自两个数组的数据。我有两个带有哈希的列表(数组):

arr1 = [ 
         { "device"=>100, "phone"=>"12345" }, 
         ..., 
         { "device"=>102, "phone"=>"12346" } 
       ]


arr2 = [ 
         { "device"=>100, "type"=>"mobile", "name"=>"nokia" }, 
         ..., 
         { "device"=>102, "type"=>"VIOP", "name"=>"smth" } 
       ]

How can I join hashes from arr1 and arr2 by "device" to get a result array:

result = [ 
           { "device"=>100, "phone"=>"12345", "type"=>"mobile", "name"=>"nokia" }, 
           ..., 
           { "device"=>102, "phone"=>"12346", "type"=>"VIOP", "name"=>"smth" } 
         ]

包含结果数组的表的页面加载速度非常慢,我需要找到生成result_array的最快方法。

请帮帮我。

4

4 回答 4

2

This would work:

(arr1 + arr2).group_by { |i| i["device"] }.map { |d,(i1,i2)| i1.merge(i2)}
#=> [{"device"=>100, "phone"=>"12345", "type"=>"mobile", "name"=>"nokia"}, {"device"=>102, "phone"=>"12346", "type"=>"VIOP", "name"=>"smth"}]
于 2013-08-20T17:27:11.207 回答
1

多种方法来解决它。这是一种非常易读的方法:

# prepare an index hash for easier access of data by device
first_by_device = arr1.group_by {|a| a['device'] }

# build a new array joining both data hashes for each item
result = arr2.map do |item|
  device = item['device']
  item.merge first_by_device(device)
end
于 2013-08-20T17:41:53.010 回答
1
(arr1 + arr2).group_by { |i| i["device"] }.values.map{|x|x.reduce(&:merge)}
于 2014-06-05T12:22:27.313 回答
0

也许它不是最漂亮的,但它有效:

result = arr1.collect{|a| h = arr2.select{|b| b["device"] ==
a["device"]}.first; h ? a.merge(h) : a }

对于大量数据,您需要更快的速度吗?

h = Hash.new
arr1.each do |a|
  h[ a["device" ] ] ||= Hash.new
  h[ a["device" ] ].merge!(a)
end
arr2.each do |a|
  h[ a["device" ] ] ||= Hash.new
  h[ a["device" ] ].merge!(a)
end
result = h.values
于 2013-08-20T16:55:32.293 回答