Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uniq elements from array of arrays

Tags:

arrays

ruby

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]]
like image 902
Abhishek Patel Avatar asked Oct 05 '11 07:10

Abhishek Patel


People also ask

How do I get the unique values of an array of arrays?

You can use . flat() to flatten your array and then use Set to get its unique values.


1 Answers

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.

like image 180
mu is too short Avatar answered Oct 21 '22 20:10

mu is too short