How to find the common elements in 2 arrays in Javascript with no duplicates (unless there are 2 of the same element)?

Viewed 26

For example, if I have 2 arrays being

['dog', 'cat', 'zebra', 'lion', 'cat']

and

['dog', 'cat', 'cat', 'frog']

then a new array should be created that only contains

['dog', 'cat', 'cat']
3 Answers

You can use two loop for the same and compare them from each other. Ex.

for(let i=0; i<ar1.length; i++)
 {
     for(let j=0; j<ar2.length; j++){
       if(ar1[i]==ar[2])
           res.push(ar[i]);

var array1 = ['dog', 'cat', 'zebra', 'lion', 'cat'];
var array2 = ['dog', 'cat', 'cat', 'frog'];

// Then you can use filter

// const filteredArray = array1.filter(value => array2.includes(value));


// (OR) `indexOf` for old browsers compability

var filteredArray = array1.filter(function(n) {
  return array2.indexOf(n) !== -1;
});

console.log(filteredArray);

const a = ['dog', 'cat', 'zebra', 'lion', 'cat'];
const b = ['dog', 'cat', 'cat', 'frog'];

let result = a.filter(function(obj){
    return b.indexOf(obj) !== -1
})
  
console.log(result)

Related