From: Joel VanderWerf Date: 2009-07-18T07:35:28+09:00 Subject: Re: [Q] removing array duplicates where a subset is unique Chuck Remes wrote: > I need to remove duplicates from an array of arrays. I can't use > Array#uniq because some fields are different and not part of the "key." > Here's an example where the first 3 elements of each sub array are the > "key" and determine uniqueness. I want to keep only the first one I get. > > >> a = [[1, 2, 3, 4, 5], [1, 2, 3, 9, 4], [1, 2, 3, 4, 4]] > => [[1, 2, 3, 4, 5], [1, 2, 3, 9, 4], [1, 2, 3, 4, 4]] > > The return value of deduplicating this array should be: [[1, 2, 3, 4, 5]] Might be faster if your intermediate is a hash, so instead of N**2 time it's N. a = [[1, 2, 3, 4, 5], [1, 2, 3, 9, 4], [1, 2, 3, 4, 4]] h = {} a.each do |row| h[row[0..2]] ||= row # record the first match end p h.values # ==> [[1, 2, 3, 4, 5]] Note that the output may come out in a different order. Does that matter? -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407