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

SK.
  • 4,174
  • 4
  • 30
  • 48
itsme
  • 48,972
  • 96
  • 224
  • 345

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
  • 14,597
  • 32
  • 109
  • 229
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"]
SK.
  • 4,174
  • 4
  • 30
  • 48