In JavaScript, we can find every element that exists in either of two arrays only once by combining the arrays and removing duplicate elements.
- Duplicate elements are included only once.
- Elements present in either array are included.
- This operation is also known as the union of two arrays.
We can find the unique elements from two arrays using the following approaches.
Approach 1: Using Set
In this approach, we use the Set object, which stores only unique values. We combine the elements of both arrays into a set and convert it back to an array.
Example: In this example, we use Set to find unique elements from two arrays.
const arr1 = [10, 20, 30, 40, 50];
const arr2 = [10, 20, 34, 32, 11];
const result = [...new Set([...arr1, ...arr2])];
console.log(result);
Output
Set(8) { 10, 20, 30, 40, 50, 34, 32, 11 }Approach 2: Using for Loop
In this approach, we iterate through the second array and use indexOf() to check whether each element already exists in the first array. If the element does not exist, we add it to the array.
Example: In this example, we use a loop to find unique elements from two arrays.
function findUniqueElements(arr1, arr2) {
for (let i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) === -1) {
arr1.push(arr2[i]);
}
}
return arr1;
}
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 2, 3, 4];
console.log(findUniqueElements(arr1, arr2));
Output
[ 1, 2, 3, 4, 5 ]
Approach 3: Using filter() and concat()
In this approach, we use concat() to combine both arrays and filter() to remove duplicate elements. The indexOf() method checks whether the current element appears for the first time.
Example: In this example, we use filter() and concat() to find unique elements.
function findUniqueElements(arr1, arr2) {
const mergedArray = arr1.concat(arr2);
return mergedArray.filter(
(element, index, array) =>
array.indexOf(element) === index
);
}
const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
console.log(findUniqueElements(arr1, arr2));
Output
[ 1, 2, 3, 4, 5, 6 ]
Approach 4: Using reduce() and includes()
In this approach, we first combine both arrays using concat(). Then, reduce() builds a new array by adding an element only when it is not already present in the accumulator.
Example: In this example, we use reduce() and includes() to remove duplicate elements.
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const combinedArray = array1.concat(array2);
const union = combinedArray.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
console.log(union);
Output
[ 1, 2, 3, 4, 5 ]