Philip Giuliani
Philip Giuliani

Reputation: 1366

Search an two dimensional array by another array

I have two arrays. One Mapper and one with my ID's.

My Array with the external ID's:

genres_array = [12,28,16]

The Mapper Array (Internal-ID, External-ID)

mapper = [
   [1,12],
   [2,18],
   [3,19],
   [4,28],
   [5,16],
   [6,90],
]

As Result i would like to have now a new array, with only the internal values of the genres_array (the genres_array had the external values first). In this case the result would be [1,4,5]

I tried a lot of ways but i really have no idea how to solve this simple problem in a clean way. Im pretty sure it will be something like

genres_array.map { |genre_id| get_internal_id_from_mapper }

PS: It could also happen that a ID won't be found in the mapper. In that i case i just want to remove it from the array. Any idea?

Upvotes: 2

Views: 69

Answers (3)

hirolau
hirolau

Reputation: 13901

Another solution involving a hash:

Hash[mapper].invert.values_at(*genres_array)

Asking for values that does not exist will return nil, if you do not want the nil just add .compact at the end.

Upvotes: 1

tckmn
tckmn

Reputation: 59283

You're looking for rassoc:

genres_array.map { |genre_id| mapper.rassoc(genre_id)[0] }

Which results in

[1, 4, 5]

EDIT: Just read the PS - try something like this:

genres_array.map { |genre_id|
    subarr = mapper.rassoc genre_id
    subarr[0] if subarr
}.compact

Then for an input of

genres_array = [12,28,100,16]

You would still get the output

[1, 4, 5]

Upvotes: 1

rorra
rorra

Reputation: 9693

Another way that won't throw an exception if the external id is not found:

genres_array = [12,28,16]

mapper = [
   [1,12],
   [2,18],
   [3,19],
   [4,28],
   [5,16],
   [6,90],
]

internal_ids = genres_array.map do |genre_id|
  element = mapper.detect { |m| m[1] == genre_id }
  element ? element[0] : nil
end.compact

Upvotes: 1

Related Questions