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.
CodePudding user response:
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]
CodePudding user response:
arr1 = [1,2,3,4,5,6]
arr2 = [[2,4],12]
arr2.flatten.each_with_object([]) { |num, arr| arr << arr1.index(num) }.compact.uniq
#=> [1, 3]