Compare two arrays and get those values that did not match JavaScript



We have two arrays of literals that contain some common values, our job is to write a function that returns an array with all those elements from both arrays that are not common.

For example βˆ’

// if the two arrays are:
const first = ['cat', 'dog', 'mouse'];
const second = ['zebra', 'tiger', 'dog', 'mouse'];
// then the output should be:
const output = ['cat', 'zebra', 'tiger']
// because these three are the only elements that are not common to both
arrays

Let’s write the code for this βˆ’

We will spread the two arrays and filter the resulting array to obtain an array that contains no common elements like this βˆ’

Example

const first = ['cat', 'dog', 'mouse'];
const second = ['zebra', 'tiger', 'dog', 'mouse'];
const removeCommon = (first, second) => {
   const spreaded = [...first, ...second];
   return spreaded.filter(el => {
      return !(first.includes(el) && second.includes(el));
   })
};
console.log(removeCommon(first, second));

Output

The output in the console will be βˆ’

[ 'cat', 'zebra', 'tiger' ]
Updated on: 2020-08-28T13:34:47+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements