0

问题主要在标题中:

给定一个数组

array = [{x: 1, y: "jacksonville"}, 
        {x: 2, y: "atlanta"}, 
        {x: 1, y: "tampa"}, 
        {x: 2, y: "atlanta"},
        {x: 2, y: "jacksonville"},
        {x: 2, y: "miami"}, ]

什么是获得以下结果的好方法

array = [{x: 3, y: "jacksonville",
         {x: 4, y: "atlanta"},
         {x: 1, y: "tampa"},
         {x: 2 ,y: "miami"}]

输入是我真正使用的简单版本,但正如您所看到的,我正在尝试删除 y 值的重复项但保留 x 值,我知道我可以在每个哈希上运行合并两个哈希将黑色传递给 Hash#merge 但我很难将所有哈希值相互比较或找到重复项。寻找高性能的解决方案。

4

2 回答 2

3

这里:

array.group_by{|e|e[:y]}.map{|k,v|{x:v.reduce(0){|a,b|a+b[:x]},y:k}}
于 2013-06-14T20:44:53.153 回答
0

First of all, you must have to create a convenient way to index y data. I would use Hash for that:

h = array.inject({}) do |ret, item|
   ret[item[:y]] ||= 0 # initialize each item
   ret[item[:y]] += item[:x] # increment count
   ret # return the hash
end

With this Hash on hand, you can generate the new array:

h.map {|key, value| {x: value, y: key}}
于 2013-06-14T20:52:56.050 回答