George Barda
George Barda

Reputation: 55

Array value comparison with a multidimension array ruby

If i have 2 arrays like let's say :

arr1 = [1,2,3,4,5,6]
arr2 = [[2,4],12]

i would like to return variable :

result=[1,3]

How can i create a variable that returns the indexes from arr1 that corresponds to the values from the arr2 nested array.

Upvotes: 0

Views: 56

Answers (1)

zhisme
zhisme

Reputation: 2800

First of all you would need to flatten your second multidimensional array, and afterwards just find that item index in the first one.

arr1 = [1,2,3,4,5,6]
arr2 = [[2,4],12]

def find_indexes(arr1, arr2)
  arr2.flatten.each_with_object([]) do |item, acc|
    index = arr1.index(item).to_i
    acc << index if index >= 0
  end
end

find_indexes(arr1, arr2)
#=> [1,3]

Upvotes: 1

Related Questions