
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compare Two Arrays and Get Non-Matching Values in 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' ]
Advertisements