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

JavascriptWeb DevelopmentObject Oriented Programming

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' ]
raja
Published on 28-Aug-2020 13:34:27
Advertisements