Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate elements from array in Ruby

I have a Ruby array which contains duplicate elements.

array = [1,2,2,1,4,4,5,6,7,8,5,6] 

How can I remove all the duplicate elements from this array while retaining all unique elements without using for-loops and iteration?

like image 766
Mithun Sasidharan Avatar asked Dec 03 '11 05:12

Mithun Sasidharan


People also ask

How do I remove a duplicate element from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.


1 Answers

array = array.uniq 

uniq removes all duplicate elements and retains all unique elements in the array.

This is one of many beauties of the Ruby language.

like image 149
Mithun Sasidharan Avatar answered Oct 16 '22 02:10

Mithun Sasidharan