[英]How to sum each unique element of an array within an array
I have an array like: 我有一个像这样的数组:
[1, 84]
[11, 29]
[11, 84]
[12, 18]
[15, 55]
[15, 4]
I Want to generate a new array from this array like: 我想从这个数组生成一个新数组,如:
[1, 84, 1]
[11, 113, 2]
[12, 18, 1]
[15, 59, 2]
where the first element of the each sub-array will be unique and their corresponding second element will be sum, and the third element will be their count. 其中每个子数组的第一个元素将是唯一的,它们对应的第二个元素将是sum,第三个元素将是它们的计数。 In case of
11
, 29 + 84 = 113
, and 11
exists 2
times, so [11, 113, 2]
. 在的情况下
11
, 29 + 84 = 113
,和11
存在2
倍,所以[11, 113, 2]
a.group_by(&:first).map { |k,v| [k,v.map(&:last).inject(:+),v.size] }
# => [[1, 84, 1], [11, 113, 2], [12, 18, 1], [15, 59, 2]]
a = [
[1, 84],
[11, 29],
[11, 84],
[12, 18],
[15, 55],
[15, 4]
]
a.group_by(&:first).values.map {|arys| [arys.first.first, arys.map{|a| a[1]}.inject(:+), arys.count]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.