Array.uniq on specific attributes

Hi,
I have a 2D array that contains arrays with 4 attributes.

ary = [
[1,“eric”, 23, “seattle”],
[2,“rob”, 23, “chicago”],
]

I need only those arrays in the 2D array where the combination of
arttibute2(name) and attribute4(city) is unique.

Please help.

Rajarshi C. wrote in post #1047757:

Hi,
I have a 2D array that contains arrays with 4 attributes.

ary = [
[1,“eric”, 23, “seattle”],
[2,“rob”, 23, “chicago”],
]

I need only those arrays in the 2D array where the combination of
arttibute2(name) and attribute4(city) is unique.

Please help.

Please elaborate your query …

One way is to manually count on your own whether you have seen a name
before or not.

Any other(programmatic) way?

The order of attributes in my inner array is:
Id, Name, Age, City

Array.uniq checks all attributes for duplicacy.
I want the check to be restricted to only 2 columns… Name and City

So, my 2D array can have
[1,“eric”, 23, “seattle”],
[1,“eric”, 23, “chicago”]

but not
[1,“eric”, 23, “seattle”],
[2,“eric”, 45, “seattle”]

Array#uniq accept block argument, later Ruby 1.9.2

[
[1,“eric”, 23, “seattle”],
[1,“eric”, 23, “chicago”]
].uniq{|l|[l[1], l[3]]}

#=> [[1, “eric”, 23, “seattle”], [1, “eric”, 23, “chicago”]]

[
[1,“eric”, 23, “seattle”],
[2,“eric”, 45, “seattle”]
].uniq{|l|[l[1], l[3]]}

#=> [[1, “eric”, 23, “seattle”]]

Thank you, Kenichi.
This is what I was looking for.
Unfortunately, I use ruby 1.8.6.
Is there a way to do it using collect, values_at and reject methods?

an approach

class Array
private

def _uniq_by(&block)
new, memo = [], {}

map(&block).each_with_index do |mapped, idx|
  unless memo[mapped]
    memo[mapped] = true
    new << self[idx]
  end
end

new

end

alias_method :_uniq, :uniq
alias_method :_uniq!, :uniq!

public

def uniq(&block)
block_given? ? _uniq_by(&block) : _uniq
end

def uniq!(&block)
if block_given?
new = _uniq_by(&block)

  if self == new
    nil
  else
    replace(new)
  end
else
  _uniq!
end

end
end

1.9.2 original

http://ideone.com/Uygbz

same return from 1.8.6, 1.8.7, 1.9.2, 1.9.3

http://ideone.com/ySoIE

Never mind my last post.
I could not delete or edit it.
Thank you Kenichi and everyone in this forum.
My problem is solved.

Thank you, Kenichi.

Can you please give an example call to the uniq method with the columns
that I want in duplicate check?

Yay, Kenichi K. solved it.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs