0

我有一个简单的数组:

[
    [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
        }
    ]
]

有没有一种简单的方法可以做到这一点,还是我必须手动迭代并做到这一点?谢谢

4

1 回答 1

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}]
于 2013-07-02T12:25:45.240 回答