汇总项目列表并收集总计的最佳方法 [英] Best way to aggregate a list of items and collect totals

查看:105
本文介绍了汇总项目列表并收集总计的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有很好的折叠(或映射,缩小等)样式的解决方案。

I'm wondering if there's a good fold (or map, reduce etc.) style solution to this problem.

给出一个购买集合(order_items),我想收集每个产品/ sku的总数。

Give a collection of purchases (order_items) I want to gather the totals for each product/sku.

示例集合:

[{sku: "A", price:10}, 
 {sku: "B", price:5}, 
 {sku: "C", price:2}, 
 {sku: "B", price:5}, 
 {sku: "A", price:10}, 
 {sku: "B", price:5}]

并得到以下结果:

{"A":20, "B":15, "C":2} 

目前我这样做:

aggregate = order_items.each_with_object({}){|i,o|
  o[i[:sku]] ||= 0
  o[i[:sku]] += i[:price]
}

哪个可以给我我想要的东西,但是我想知道是否有更优雅的方法可以做到这一点?

Which gives me what I want, but I want to know if there's a more elegant way to do this?

很显然,如果我对单个SKU进行预过滤,则可以执行经典的 reduce 即。

Obviously, if I pre-filter to a single SKU I can do a classic reduce ie.

# assuming sku is a flat array of values for a single sku type...
aggregate_sku = sku.reduce(:+)

但是,我不想预先过滤原始集合。有没有办法做到这一点,或者我已经尽一切可能了?

However, I don't want to have to pre-filter the original collection. Is there a way to achieve this or am I already doing everything possible?

任何帮助都是值得的。

编辑以增加问题的清晰度。如果您认为需要投票结束,请先发表评论,以便我澄清。

Edited to add clarity to the question. If you feel the need to vote to close, please post a comment first, so I can clarify.

次文本:我不确定地图减少等,具有我不了解的功能(或更可能的技巧),谢谢。

Subtext: I'm not sure if map, reduce etc, has features (or more likely techniques) I don't yet understand, Thank you.

推荐答案

order_items = [
 {sku: "A", price:10}, 
 {sku: "B", price:5}, 
 {sku: "C", price:2}, 
 {sku: "B", price:5}, 
 {sku: "A", price:10}, 
 {sku: "B", price:5}
]

aggregate = order_items.each_with_object(Hash.new(0)) do |item, acc|
  acc[ item[:sku] ] += item[:price]
end

--output:--
{"A"=>20, "B"=>15, "C"=>2}

这篇关于汇总项目列表并收集总计的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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