簡體   English   中英

如何在Ruby中合並子數組中的子數組?

[英]How to merge sub-arrays within an array in Ruby?

我有一個數組,出於參數考慮,它看起來像這樣:

a = [[1,100], [2,200], [3,300], [2,300]]

在這四個子數組中,我想合並第一個元素為重復項的任何子數組。 因此,在上面的示例中,我想合並第二和第四子數組。 但是,需要注意的是,在匹配子數組中第二個元素不同的情況下,我想保持較高的值。

因此,我希望看到以下結果:

a = [[1,100], [3,300], [2,300]]

這個小難題超出了我的Ruby技能,因此請向社區尋求幫助。 任何有關如何解決此問題的指導都將受到贊賞。

謝謝

# Get a hash that maps the first entry of each subarray to the subarray
# requires 1.8.7+ or active_support (or facets, I think)
hash = a.group_by { |first, second| first }
# Take each entry in the hash and select the biggest entry for each unique key
hash.map {|k,v| v.max }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM