如果它们具有相同的值,则在哈希数组中求和值 [英] Sum values in array of hash if they have the same value

查看:123
本文介绍了如果它们具有相同的值,则在哈希数组中求和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Rails在哈希数组中加上数值

  array = [
{loading:10,avg:15,total:25},
{loading:20,avg:20,总数:40},
{loading:30,avg:25,total:55}
]

sum = Hash.new(0)

array.each_with_object(sum)do | hash,sum |
hash.each {| key,value | sum [key] + = value}
end
#=> {:loading => 60,:avg => 60,:total => 120}

我想要做什么,我不知道怎么做,是总和的关键,如果加载和avg出现在这个数组中多次相同的值。例如。

  array = [
{loading:10,avg:15,total:25},
{loading:20,avg:20,total:40},#看到这里
{loading:30,avg:25,total:55},
{loading:20,avg:20,总数:80},#见这里
{loading:10,avg:20,total:46}
]

结果如下:

$ p $ [
{loading:10,avg: 15,总数:25},
{loading:20,avg:20,total:120},#结果在
{loading:30,avg:25,total:55},
{loading:10,avg:20,total:46}
]

修改此行

  hash.each {| key,value | sum [key] + = value} 

添加一个条件来检查值是否重复但我didn没有成功。



任何帮助,想法或任何东西都会受到欢迎。 这似乎工作

  array.group_by {| item | [item [:loading],item [:avg]]} .values.flat_map {| items | items.first.merge(total:items.sum {| h | h [:total]})} 
=> [{:loading => 10,:avg => 15,:total => 25},{:loading => 20,:avg => 20,:total => 120},{:loading => 30,::avg => 25,:total => 55},{:loading => 10,:avg => 20,:total => 46}]


I saw this piece of code in this post, because I'm trying to sum values in an array of hashes based on some criteria.

Rails sum values in an array of hashes

array = [
  {loading: 10, avg: 15, total: 25 },
  {loading: 20, avg: 20, total: 40 },
  {loading: 30, avg: 25, total: 55 }
]

sum = Hash.new(0)

array.each_with_object(sum) do |hash, sum|
  hash.each { |key, value| sum[key] += value }
end
 # => {:loading=>60, :avg=>60, :total=>120}

What I'm trying to do and I don't know how, is to sum total key if loading and avg appear with the same values more than once in this array. For instance.

 array = [
      {loading: 10, avg: 15, total: 25 },
      {loading: 20, avg: 20, total: 40 }, # See here
      {loading: 30, avg: 25, total: 55 },
      {loading: 20, avg: 20, total: 80 }, # See here
      {loading: 10, avg: 20, total: 46 }
    ]

The result would be:

[
  {loading: 10, avg: 15, total: 25 },
  {loading: 20, avg: 20, total: 120 }, # Results in this
  {loading: 30, avg: 25, total: 55 },
  {loading: 10, avg: 20, total: 46 }
]

I tried to modify this line

hash.each { |key, value| sum[key] += value }

Adding a conditional that checks if the value is repeated but I didn't succeed.

Any help, ideas or anything will be welcome.

解决方案

This seems work

array.group_by { |item| [item[:loading], item[:avg]] }.values.flat_map { |items| items.first.merge(total: items.sum { |h| h[:total] }) }
=> [{:loading=>10, :avg=>15, :total=>25}, {:loading=>20, :avg=>20, :total=>120}, {:loading=>30, :avg=>25, :total=>55}, {:loading=>10, :avg=>20, :total=>46}]

这篇关于如果它们具有相同的值,则在哈希数组中求和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆