-5

i have a two arrays.

 var a = ["a","b","c","d"];
 var b = ["c","d","f","k"];

These are my two arrays.Now i need to check any single matching values in two arrays.it should break after finding single match value.

My expect result was c and d matches.

Sathish Sundharam
  • 1,060
  • 2
  • 12
  • 22

5 Answers5

1

You can use Array#find to iterate one of the arrays, and Array#indexOf or Array#includes to find if the item exists in 2nd array:

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);

And a fancy version with arrow functions and consts:

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Why use [ES7](http://2ality.com/2016/01/ecmascript-2016.html) with includes, and do not use arrow functions to simplify `findMatch`? :) `arr1.find(item => arr2.includes(item));` – Orelsanpls Sep 12 '17 at 12:02
0

If you just wanna know if there is duplicate content, this will work :

 a.some(x => b.some(y => y === x));

Will gives you true in case of duplicate content.


If you want every matching content in an array

a.filter(x => b.some(y => x === y));

will gives you ['c', 'd']

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
0

you can do it in the following way

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);
marvel308
  • 10,288
  • 1
  • 21
  • 32
0

I loop through the first array once and check the index of each value in the second array.

If the index is > -1, then push it onto the returned array.

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) );
l.g.karolos
  • 1,131
  • 1
  • 10
  • 25
0

You can use filter() and every() to achieve what you want:

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);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62