From: John W Higgins Date: 2009-09-26T00:55:09+09:00 Subject: Re: How to remove duplicate elements in a 2D array --001636284e58dab62f047468f80a Content-Type: text/plain; charset=ISO-8859-1 Sorry about the last response - hit the wrong button..... On Fri, Sep 25, 2009 at 8:34 AM, Li Chen wrote: > Hi all, > > I have a 2D array as follow: > > arr=[ > > [ 'a',1,2,3], > ['b',4,5,6], > ['c',3,2,1], > ['a',1.3,2.2,3,3], > ... > ['a', 2,1,3], > ... > ['a',2.1,1.5,3] > > ] > > As you can see there are several rows containing element 'a', > and the last row containing 'a'' is the lastest one. I wonder if it > is possible to return a new array which contains the latest row having > 'a' , > together with other rows. > > Lets try this again shall we.... seen = [] # this stores the first elements as we pass through them #we reverse the array because you want the last elements to be the ones returned #select will add an element to the return value if the block is true arr.reverse.select{ |x| check = !(seen.include?(x[0])) #we check to see if we've seen this first element before seen << x[0] #add the first element to our "seen" list - we don't care if it's in here multiple times check #the block equals the check value }.reverse #since we reversed once we want to do so again to get the correct order back John > > Thanks, > > Li > -- > Posted via http://www.ruby-forum.com/. > > --001636284e58dab62f047468f80a--