Unique elements from two unsorted arrays can be found by comparing the elements of both arrays and keeping only those that occur in one array.
- Use filter() or Set to compare elements efficiently.
- A frequency map can identify elements that occur only once across both arrays.
- Lodash provides a concise xor() method for this operation.
Approach 1: Using filter() Method
The filter() method can be used to find elements that are present in one array but not in the other. The filtered results are then combined using concat().
let a1 = [54, 71, 58, 95, 20];
let a2 = [71, 51, 54, 33, 80];
let uni1 = a1.filter(o => a2.indexOf(o) === -1);
let uni2 = a2.filter(o => a1.indexOf(o) === -1);
const res = uni1.concat(uni2);
console.log(res);
Output
[ 58, 95, 20, 51, 33, 80 ]
Approach 2: Using Sets
A Set stores unique values and provides an efficient way to check whether an element exists in another array.
const a1 = [54, 71, 58, 95, 20];
const a2 = [71, 51, 54, 33, 80];
const set1 = new Set(a1);
const set2 = new Set(a2);
const uni1 = a1.filter(item => !set2.has(item));
const uni2 = a2.filter(item => !set1.has(item));
const res = [...uni1, ...uni2];
console.log(res);
Output
[ 58, 95, 20, 51, 33, 80 ]
Approach 3: Using a Frequency Map
A frequency map counts how many times each element occurs across both arrays. Elements with a frequency of 1 are unique to one of the arrays.
const a1 = [54, 71, 58, 95, 20];
const a2 = [71, 51, 54, 33, 80];
const a = [...a1, ...a2];
const freq = a.reduce((acc, el) => {
acc[el] = (acc[el] || 0) + 1;
return acc;
}, {});
const elem = Object.keys(freq)
.filter(key => freq[key] === 1)
.map(Number);
console.log(elem);
Output
[ 20, 33, 51, 58, 80, 95 ]
Approach 4: Using Lodash
Lodash provides the _.xor() method, which returns elements that occur in only one of the two arrays.
const _ = require('lodash');
const arr1 = [54, 71, 58, 95, 20];
const arr2 = [71, 51, 54, 33, 80];
const uniqueElements = _.xor(arr1, arr2);
console.log(uniqueElements);
Output:
[58, 95, 20, 51, 33, 80]