我有一个简单的数组:
[
[0] {
"user_id" => 4,
"type" => 1
},
[1] {
"user_id" => 4,
"type" => 1
},
[2] {
"user_id" => 1,
"type" => 1
},
[3] {
"user_id" => 2,
"type" => 65
},
[4] {
"user_id" => 1,
"type" => 23
},
[5] {
"user_id" => 4,
"type" => 4
}
]
我想要做的就是删除具有相同user_id和类型的元素,然后将它们组合在一起并将它们放回到数组中。所以结果就是这种情况:
[
[0] {
"user_id" => 1,
"type" => 1
},
[1] {
"user_id" => 2,
"type" => 65
},
[2] {
"user_id" => 1,
"type" => 23
},
[3] {
"user_id" => 4,
"type" => 4
},
[4] [
[0] {
"user_id" => 4,
"type" => 1
},
[1] {
"user_id" => 4,
"type" => 1
}
]
]
是否有一种简单的方法可以执行此操作,还是必须手动迭代并执行此操作?感谢
答案 0 :(得分:2)
require 'pp'
a = [
{
"user_id" => 4,
"type" => 1
},
{
"user_id" => 4,
"type" => 1
},
{
"user_id" => 1,
"type" => 1
},
{
"user_id" => 2,
"type" => 65
},
{
"user_id" => 1,
"type" => 23
},
{
"user_id" => 4,
"type" => 4
}
]
pp a.group_by{|i| i.values_at("user_id","type") }.values
output:
[[{"user_id"=>4, "type"=>1}, {"user_id"=>4, "type"=>1}],
[{"user_id"=>1, "type"=>1}],
[{"user_id"=>2, "type"=>65}],
[{"user_id"=>1, "type"=>23}],
[{"user_id"=>4, "type"=>4}]]
<强>更新强>
require 'pp'
a = [
{
"user_id" => 4,
"type" => 1
},
{
"user_id" => 4,
"type" => 1
},
{
"user_id" => 1,
"type" => 1
},
{
"user_id" => 2,
"type" => 65
},
{
"user_id" => 1,
"type" => 23
},
{
"user_id" => 4,
"type" => 4
}
]
arr = a.map do |i|
tot = a.count(i)
next ([i] * tot) if tot > 1 ; i
end.uniq
pp arr
的输出:强> 的
[[{"user_id"=>4, "type"=>1}, {"user_id"=>4, "type"=>1}],
{"user_id"=>1, "type"=>1},
{"user_id"=>2, "type"=>65},
{"user_id"=>1, "type"=>23},
{"user_id"=>4, "type"=>4}]