asiniy asiniy - 5 months ago 16
Ruby Question

Finding `uniq` values in array with their indexes

Let say I have an array

[1, 2, 3, 4, 3, 2]


I wonder how I can get the hash
{ 1 => 0, 4 => 3 }
(
value => index
). I need the index of the earlier occurrence.

Answer

Could also try this

unique = array.select { |a| array.count(a) === 1 }
indexes = unique.map { |u| array.index(u) }
Hash[unique.zip(indexes)]

My algorithm is to first generate a new array of the single elements. I do that by filtering the array for the one's where the count is equal to 1. We can use the array#count method.

I then create a second array, where I map the values of the first array, to their indexes in the original array.

I then combine the values using the array#zip function and convert to a hash with Hash.

Output

{ 1 => 0, 4 => 3 }