优化散列按日期分组阵列 [英] Optimize grouping array of hashes by date
本文介绍了优化散列按日期分组阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于阵列
[
{日期:2014年1月1日',一:5,B:1},
{日期:2014年1月1日,XYZ:11},
{日期:2014年10月10日,QBZ:5},
{日期:2014年10月10日',V:4,问:1,strpm:-99}
]
我想按日期和输出哈希值的数组
输出中= [
{日期:2014年1月1日,一:5,B:1,XYZ:11},
{日期:二零一四年十月十日,QBZ:5,V:4,问:1,strpm:-99},
]
我解决它在Ruby中,有一个解决方案,但它似乎效率不高。
高清arrayt(inputarray)
outputarray = [];
inputarray.each做| x |
tindex =包括(outputarray,X [:日期])
如果tindex == -1
outputarray.push(X)
其他
outputarray [tindex] .merge!(X)
结束
结束
返回outputarray
结束
包括高清(阵列,日)
array.each_with_index做|临时,指数|
如果date ==温度[:日期]
回报指数
结束
结束
返回-1
结束
任何帮助,更优雅的解决办法是AP preciated
解决方案
[
{日期:2014年1月1日',一:5,B:1},
{日期:2014年1月1日,XYZ:11},
{日期:2014年10月10日,QBZ:5},
{日期:2014年10月10日',V:4,问:1,strpm:-99}
]
.group_by(安培;:第一).MAP {| _,V | v.inject(:合并)}
Given array
[
{date: '2014-01-01', a: 5, b:1},
{date: '2014-01-01', xyz: 11},
{date: '2014-10-10', qbz: 5},
{date: '2014-10-10', v: 4, q: 1, strpm: -99}
]
I want to group by date and output an array of hashes
ouput = [
{date: 2014-01-01, a: 5, b:1, xyz: 11 },
{date: 2014-10-10, qbz: 5, v: 4, q: 1, strpm: -99},
]
I am solving it in Ruby and have a solution but it seems inefficient.
def arrayt(inputarray)
outputarray=[];
inputarray.each do |x|
tindex = includes(outputarray,x[:date])
if tindex == -1
outputarray.push(x)
else
outputarray[tindex].merge!(x)
end
end
return outputarray
end
def includes(array,date)
array.each_with_index do |temp,index|
if date==temp[:date]
return index
end
end
return -1
end
Any help with a more elegant solution would be appreciated
解决方案
[
{date: '2014-01-01', a: 5, b:1},
{date: '2014-01-01', xyz: 11},
{date: '2014-10-10', qbz: 5},
{date: '2014-10-10', v: 4, q: 1, strpm: -99}
]
.group_by(&:first).map{|_, v| v.inject(:merge)}
这篇关于优化散列按日期分组阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文