I want to find unique elements from an array of arrays by the first element in the inner arrays.
for example
a = [[1,2],[2,3],[1,5]
I want something like
[[1,2],[2,3]]
You can use . flat() to flatten your array and then use Set to get its unique values.
The uniq
method takes a block:
uniq_a = a.uniq(&:first)
Or if you want to do it in-place:
a.uniq!(&:first)
For example:
>> a = [[1,2],[2,3],[1,5]]
=> [[1, 2], [2, 3], [1, 5]]
>> a.uniq(&:first)
=> [[1, 2], [2, 3]]
>> a
=> [[1, 2], [2, 3], [1, 5]]
Or
>> a = [[1,2],[2,3],[1,5]]
=> [[1, 2], [2, 3], [1, 5]]
>> a.uniq!(&:first)
=> [[1, 2], [2, 3]]
>> a
=> [[1, 2], [2, 3]]
If you're stuck back in 1.8.7 land where uniq
doesn't take a block, then you can do it this way:
a.group_by(&:first).values.map(&:first)
For example:
>> a = [[1,2],[2,3],[1,5]]
=> [[1, 2], [2, 3], [1, 5]]
>> a.group_by(&:first).values.map(&:first)
=> [[1, 2], [2, 3]]
Thanks for the extra prodding Jin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With