将哈希分组在一起以连接关键值

时间:2015-05-07 14:59:29

标签: ruby reduce

我有一系列哈希,如下所示:

records = [
    { id: "PU525", note: "Foo" },
    { id: "PU525", note: "Bar" },
    { id: "DT525", note: "Hello World" },
    { id: "PU680", note: "Fubar" }
]

最终结果应为:

result = [
    { id: "PU525", note: "FooBar" },
    { id: "DT525", note: "Hello World" },
    { id: "PU680", note: "Fubar" }
]

我开始使用以下内容与Enumerable#group_by进行一些比较:

results = records.group_by { |record| record[:id] }

# Results in:
# {
#     "PU525": [
#         { id: "PU525", note: "Foo" },
#         { id: "PU525", note: "Bar" }
#     ],
#     "DT525": { id: "DT525", note: "Hello World" },
#     "PU680": { id: "PU680", note: "Fubar" }
# }

下一步是使用注入来进一步减少数据,但我想知道是否有一种更简单的方法可以将原始阵列减少到我想要的位置。没有这么多步骤的结果?

3 个答案:

答案 0 :(得分:3)

你差不多完成了:

 std::cout << static_cast< int >( u );

UPD 毕竟,你让我迷上了这种愚蠢的records = [ { id: "PU525", note: "Foo" }, { id: "PU525", note: "Bar" }, { id: "DT525", note: "Hello World" }, { id: "PU680", note: "Fubar" } ] arr = records.group_by { |record| record[:id] } .map do |k, v| [k, v.reduce('') { |memo, h| memo + h[:note] } ] end .map do |a| { id: a.first, note: a.last } end #⇒ [ # { id: "PU525", note: "FooBar" }, # { id: "DT525", note: "Hello World" }, # { id: "PU680", note: "Fubar" } # ] 方法。一切都变得更容易。

group_by

答案 1 :(得分:1)

使用#group_by后,这是另一种方式:

records = [
    { id: "PU525", note: "Foo" },
    { id: "PU525", note: "Bar" },
    { id: "DT525", note: "Hello World" },
    { id: "PU680", note: "Fubar" }
]

hsh = records.group_by { |record| record[:id] }.map do |_, v|
  v.inject do |h1, h2|
    h1.update(h2) { |k, o, n| k == :note ? o << n : n }
  end
end

p hsh
# >> [{:id=>"PU525", :note=>"FooBar"}, {:id=>"DT525", :note=>"Hello World"}, {:id=>"PU680", :note=>"Fubar"}]

答案 2 :(得分:0)

以上是上述几种变体。

使用Enumerable#group_by

merge!

使用Hash#update (又名records.each_with_object({}) { |g,h| h.update(g[:id]=>g) { |_,og,ng| { id: g[:id], note: og[:note]+ng[:note] } } }.values #=>[{:id=>"PU525", :note=>"FooBar"}, # {:id=>"DT525", :note=>"Hello World"}, # {:id=>"PU680", :note=>"Fubar"}]

var myNums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var Remve = [];
var i;

for(i=0;i<myNums.length;i++){
    if(myNums[i] % 3 == 0){
        Remve.push(myNums[i])
    }else{
        myNums.push(myNums[i])
    }
}

document.write(myNums);
document.write(Remve);