Jackson
Jackson

Reputation: 483

Find index of array in multidimensional array by string value

I need the index of an array in a multidimensional array if it contains a unique string.

array:

[
    {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
    {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
    {:id=>16, :name=>"Navy", :hex_value=>"285974"}
]

If hex_value of 'FFF600' exists, return the arrays position, which in this case would be 1.

This is where I am at, but it's returning [].

index = array.each_index.select{|i| array[i] == '#FFF600'}

Upvotes: 1

Views: 555

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33491

That's returning nil, because there's no element i (index) in the array with value #FFF600 (nor FFF600), you need to access to the hex_value key value:

p [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
].yield_self { |this| this.each_index.select { |index| this[index][:hex_value] == 'FFF600' } }
# [1]

Giving you [1], because of using select, if you want just the first occurrence, you can use find instead.

I'm using yield_self there, to avoid assigning the array to a variable. Which is equivalent to:

array = [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
]
p array.each_index.select { |index| array[index][:hex_value] == 'FFF600' }
# [1]

Being Ruby, you can use the method for that: Enumerable#find_index

p [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
].find_index { |hash| hash[:hex_value] == 'FFF600' }
# 1

Upvotes: 3

Related Questions