我有两个数组。
var a = ["a","b","c","d"];
var b = ["c","d","f","k"];
这是我的两个数组。现在我需要检查两个数组中的任何单个匹配值。在找到单个匹配值后应该中断。
我期待的结果是c和d匹配。
答案 0 :(得分:1)
您可以使用Array#find来迭代其中一个数组,Array#indexOf 或Array#includes查找该项是否存在于第二个数组中:
var a = ["a", "b", "c", "d"];
var b = ["c", "d", "f", "k"];
function findMatch(arr1, arr2) {
return arr1.find(function(item) {
return arr2.indexOf(item) === -1;
});
}
var result = findMatch(a, b);
console.log(result);
带箭头功能和功能的花哨版本:
const a = ["a","b","c","d"];
const b = ["c","d","f","k"];
const findMatch = (arr1, arr2) => arr1.find((item) => arr2.includes(item));
const result = findMatch(a, b);
console.log(result);
答案 1 :(得分:0)
如果你只是想知道是否有重复的内容,这将有效:
a.some(x => b.some(y => y === x));
如果内容重复,会为您提供 true 。
如果你想要一个数组中的每个匹配内容
a.filter(x => b.some(y => x === y));
将为您提供['c', 'd']
答案 2 :(得分:0)
你可以通过以下方式完成
var a = ["a","b","c","d"];
var b = ["c","d","f","k"];
let ans = a.reduce(function(x, y){
if(x == null){
if(b.indexOf(y) > -1){
return y;
}
}
return x;
}, null);
console.log(ans);

答案 3 :(得分:0)
我遍历第一个数组并检查第二个数组中每个值的索引。
如果索引是> -1,然后将其推送到返回的数组。
Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf( this[i] ) > -1){
ret.push( this[i] );
}
}
return ret;
};
var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];
console.log( array1.diff(array2) );

答案 4 :(得分:0)
您可以使用filter()
和every()
来实现您的目标:
var a = ["a","b","c","d"];
var b = ["c","dx","f","k"];
var isMatched = false;
result = a.filter(x =>{
b.every(s => { return isMatched = s!==x});
});
console.log(!isMatched);