
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
Find Uncommon Elements in Two Arrays using JavaScript
Let’s say, we have two arrays of numbers −
const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
We are required to write a JavaScript function that takes in two such arrays and returns the element from arrays that are not common to both.
Let’s write the code for this function −
Example
Following is the code −
const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34]; const unCommonArray = (first, second) => { const res = []; for(let i = 0; i < first.length; i++){ if(second.indexOf(first[i]) === -1){ res.push(first[i]); } }; for(let j = 0; j < second.length; j++){ if(first.indexOf(second[j]) === -1){ res.push(second[j]); }; }; return res; }; console.log(unCommonArray(arr1, arr2));
Output
Following is the output in the console −
[ 6, 5, 1 ]
Advertisements