如何在一个数组中查找另一个数组中任意元素的索引?

3

我有一个数组:

["a", "b", "c", "d"]

如何确定上述数组的第一个元素在第二个数组中出现的索引:

["next", "last", "d", "hello", "a"]

第一个数组中第一个元素在上述数组中出现的索引是2;"d"属于第一个数组,在位置2处出现。


从示例中看来,您似乎想要找到第二个数组中第一个出现在第一个数组中的元素的索引,但这不是您所说的。难道不是 "a"(而不是 "d")“第一个在上述[第二个]数组中出现的第一个数组元素”吗? - Cary Swoveland
3个回答

4

有几种方法可以做到这一点,但是朴素的方法可能足以让您开始:

tests = ["a", "b", "c", "d"]
in_array = ["next", "last", "d", "hello", "a"]

in_array.each_with_index.find do |e, i|
  tests.include?(e)
end
# => ["d", 2]

您可以通过将tests设置为Set来加快速度,这样可以避免很多O(N)的查找:

tests = Set.new([ ... ])

同样的代码也可以使用 include?,但是在更长的列表上速度会更快。

谢谢。那么我该如何获取实际索引呢?我尝试了“found_index = in_array.each_with_index.find do |e, i| tests.include?(e)[1] end”,但是我一直收到“NoMethodError: undefined method `[]' for false:FalseClass”错误提示。 - user7055375
如果你想的话,可以通过这个操作直接获取结果:found_test, found_index = in_array.each_with_index... 这样你就能得到两个变量而不是一个由两个元素组成的数组。记住 include? 会返回 truefalse,所以你不能用它来引用。另一种方式是使用 found = in_array...,然后调用 found[0]found[1],可能这正是你之前想做的,但你过早地这么做了。 - tadman

0

这种方法被封装在一个函数中,返回一个数组,其中包含两个数组之间所有共有元素的索引。

def find_positions(original_array, look_up_array)
  positions_array = []
  original_array.each do |x|
    if look_up_array.index(x) != nil
      positions_array << look_up_array.index(x)
    end
  end
  positions_array
  # positions_array.first => for the first matched element
end

如果您只想返回首个匹配元素,可以使用positions_array.first,但这样做无法避免额外的查找。
PS:您还可以使用#collect来避免使用额外的数组(positions_array)。

-1
你可以遍历想要比较的数组,使用.select或.find迭代器方法。.find将选中在数组中第一个匹配的元素,而.select将匹配数组中的所有元素。如果你想在选择中添加索引,可以添加.each_with_index。'.index(a)'返回该元素(如果存在),否则返回nil。
alphabet = %w(a b c d)
%w(next last d hello a).each_with_index.find {|a, _index| alphabet.index(a) }
 => ["d", 2]
%w(next last d hello a).each_with_index.select {|a, _index| alphabet.index(a) }[0]
 => ["d", 2]
# if you just need the index of the first match
%w(next last d hello a).index {|a| alphabet.index(a) }
 => 2 

2
这个答案可以通过给你的代码添加描述来改进。 - Steve Buzonas
嗨,您正在选择数组中找到某些内容的每个元素,但我只想要找到第一个元素。 - user7055375
如果你只需要第一个元素,可以在块的末尾添加 [0],或者使用 find 进行迭代,这样会更清晰一些。 - David Gross
那仍然不会 '返回一个索引。它返回类似于' ["c",2]' 的东西。 - user7055375
非常抱歉,我误解了你的意思,原来你只需要返回索引。我刚刚更新了我的答案,只返回索引。 - David Gross

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接