user6107657 - 1 year ago 63

Ruby Question

`A=[[a,3],[a,2],[a,1],[b,1],[b,3]]`

I want to

`uniq`

result should be

`[[a,3],[b,3]]`

Here is my code:

`A.uniq{|i| i.first}`

=> [[a,1],[b,1]]

Answer Source

You could use Enumerable#group_by and Enumerable#max_by.

```
A=[['a',3],['a',2],['a',1],['b',1],['b',3]]
A.group_by(&:first).map { |_,v| v.max_by(&:last) }
#=> [["a", 3], ["b", 3]]
```

The two steps:

```
h = A.group_by(&:first)
#=> {"a"=>[["a", 3], ["a", 2], ["a", 1]], "b"=>[["b", 1], ["b", 3]]}
h.map { |_,v| v.max_by(&:last) }
#=> [["a", 3], ["b", 3]]
```