0

I have two arrays like this:

var x = ['1','2','6'];
var y = ['4', '5','6'];

How do I find duplicates in two arrays in pure JavaScript and I would like to avoid using a loop?

Output - duplicates: 6

Simpal Kumar
  • 3,765
  • 3
  • 26
  • 48
itsme
  • 47,321
  • 93
  • 214
  • 341

2 Answers2

2

Try something like this:

var x = ['1','2','6'];
var y = ['4', '5','6'];

var overlap = x.filter(function(v,i,a){
  return y.indexOf(v) > -1;
});

console.log(overlap); // ['6']

Does this work for your purpose?

MDN docs for filter

1252748
  • 13,412
  • 30
  • 97
  • 213
1

Try this

var x = ['1','2','6'];
var y = ['4', '5','6'];
var duplicate = [];
for (var i=0; i<y.length; i++) {
    var index = x.indexOf(y[i]);
    if (index > -1) {
        duplicate.push(x[index]);
    }
}

Output: ["6"]
Simpal Kumar
  • 3,765
  • 3
  • 26
  • 48