我有一个数组数组,每个数组由3个值组成,
[owner, registered_user, license_type]
以下是一些示例数据:
[["john", "john", "drivers license"],["john", "john", "boat license"],
["john", "ryan", "drivers license"], ["john", "ryan", "boat license"],
["Sam", "Sam", "drivers license"],["Sam", "Sam", "boat license"],
["Sam", "Tim", "drivers license"], ["Sam", "Tim", "boat license"]]
我正在寻找一些方法来合并这些数据以删除重复数据并最终得到类似的结果:
=> { "john"=>{
"john"=>["drivers license", "boat license"],
"ryan"=>["drivers license", "boat license"]
},
"Sam" =>{
"Sam" =>["drivers license", "boat license"],
"Tim" =>["drivers license", "boat license"]
}
}
很抱歉,如果其中任何一个在语法上不正确或无效的Ruby,我是新的,不知道如何正确格式化。
答案 0 :(得分:0)
通过使用递归,可以有任意数量的嵌套级别。我最初假设结果是一个嵌套数组。
返回嵌套数组
def rearrange(arr)
return arr.flatten if arr.first.size == 1
arr.group_by(&:first).map { |f,a| [f, rearrange(a.map { |b| b.drop 1 })] }
end
arr = [["john", "john", "drivers license"], ["john", "john", "boat license"],
["john", "ryan", "drivers license"], ["john", "ryan", "boat license"],
["Sam", "Sam", "drivers license"], ["Sam", "Sam", "boat license"],
["Sam", "Tim", "drivers license"], ["Sam", "Tim", "boat license"]]
rearrange arr
#=> [
# ["john", [
# ["john", ["drivers license", "boat license"]],
# ["ryan", ["drivers license", "boat license"]]
# ]
# ],
# ["Sam", [
# ["Sam", ["drivers license", "boat license"]],
# ["Tim", ["drivers license", "boat license"]]
# ]
# ]
# ]
返回嵌套哈希
OP应该考虑返回一个哈希值,这样可以更容易地提取信息。这可以通过以下方式完成,再次使用递归。
def rearrange(arr)
return arr.flatten if arr.first.size == 1
h = arr.group_by(&:first)
h.each_key { |k| h[k] = { |_,a| [f, rearrange(a.map { |b| b.drop 1 })] }
end
h = rearrange(arr)
#=> { "john"=>{
# "john"=>["drivers license", "boat license"],
# "ryan"=>["drivers license", "boat license"]
# },
# "Sam" =>{
# "Sam" =>["drivers license", "boat license"],
# "Tim" =>["drivers license", "boat license"]
# }
# }
通过返回哈希,您可以轻松检索感兴趣的数据。例如,
h["Sam"]["Tim"]
#=> ["drivers license", "boat license"]