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.
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.
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 }
Hash[unique.map{ |u| [u,array.index(u)]}] rather than map and then zip just zip them in the mapping. OR even a 1 liner would be Hash[array.select{|a| array.count(a) == 1 }.map{ |u| [u,array.index(u)]}]a.each_with_index.with_object({}) { |(e, i), h| h.key?(e) ? h[e] = nil : h[e] = i }
.reject! { |k, v| v.nil? }
nil) instead of -1..each_with_index.with_object({}){|(e, i), h| to make it look better.a.each_with_index.with_object({}) { |(e, i), h| h[e] = i if a.count(e) == 1 }h[e] = h.has_key?(e) ? nil : i and instead of rejecting nil values, you could select non-nil values using select { |k, v| v }reject! returns nil if nothing was rejected, you have to use the non-bang methods (either reject or select)