查找与另一个数组中的任何项匹配的数组中的项
Find item in an array that matches any item in another array
假设我有一个字符串数组
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));
相关文章:
- Javascript/jQuery:如何从数组的项中获取排列
- 使用名称/值从 json 数组添加项
- 在 JavaScript 中,当循环通过 FOR 循环时,如何将数组中项的值传递给匿名函数
- 如何按属性从可观察数组返回项
- 数组列表项搜索
- 对可观察数组中项的属性进行自定义绑定,如何访问该项
- knockoutjsforeach数组选择项值绑定
- 检查字符串中的数组匹配项并继续检查
- 更新数组的项
- BackboneJS如何删除Model数组的项
- 从数组随机项-不能找到变量:getElementById
- Splice()不更新knockout.js中数组的项顺序
- 如何获取数组中项目的id
- 检查多维数组中项旁边的位置
- 访问压入数组的项
- 在Angular中基于ng-repeater索引查找数组的项
- RethinkDB:订阅数组中项的更改
- JavaScript:在另一个数组中插入数组's项
- 使用jquery的内部数组第一项从数组中移除数组
- 根据另一个值存储数组的项