查找与另一个数组中的任何项匹配的数组中的项

Find item in an array that matches any item in another array

本文关键字:数组 任何项 查找 另一个      更新时间:2023-09-26

假设我有一个字符串数组

words = ["quick", "brown", "fox"]

和另一个字符串数组

animals = ["rabbit", "fox", "squirrel"]

我正在寻找一个函数,它将返回words中任何匹配的索引。像这样:

words.findMatches(animals) // returns 2, the index at which "fox" occurs

添加到tetta的答案-我只是过滤掉了不匹配(-1),所以返回的数组只包含匹配的索引。

var words = ["quick", "brown", "fox"];
var animals = ["rabbit", "fox", "squirrel"];
function getMatches(array1, array2) {
  var result = array1.map(function (el) {
    return array2.indexOf(el);
  });
  result.filter(function (el) {
    return el !== -1
  });
  return result;
}
console.log(getMatches(animals, words));

同样可以通过链接数组方法来完成:

function getMatches(array1, array2) {
  return array1.map(function (el) {
    return array2.indexOf(el);
  }).filter(function (el) {
    return el !== -1
  });
}
console.log(getMatches(animals, words));

试试这个方法。它将输出[- 1,2,-1]。你想怎么用就怎么用。

var words = ["quick", "brown", "fox"];
var animals = ["rabbit", "fox", "squirrel"];
function getMatches(array1, array2) {
  return array1.map(function (el) {
    return array2.indexOf(el);
  });
}
console.log(getMatches(animals, words));