Open In App

How to print unique elements from two unsorted arrays using JavaScript ?

Given two unsorted arrays, the task is to write a JavaScript program to print the unique (uncommon) elements in the two arrays.

These are the way by which we print unique elements from two unsorted arrays using JavaScript:



Approach 1: Using for loop

Example: The implementation of the above approach is given below.




function unique(arr1, arr2, uniqueArr) {
    for (let i = 0; i < arr1.length; i++) {
        let flag = 0;
        for (let j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
                arr2.splice(j, 1);
                j--;
                flag = 1;
            }
        }
 
        if (flag == 0) {
            uniqueArr.push(arr1[i]);
        }
    }
    uniqueArr.push(arr2);
    return uniqueArr;
}
 
let arr1 = [54, 71, 58, 95, 20];
let arr2 = [71, 51, 54, 33, 80];
 
let uniqueArr = [];
 
console.log("Unique elements in the two arrays are: "
    + unique(arr1, arr2, uniqueArr).flat());

Output

Unique elements in the two arrays are: 58,95,20,51,33,80

Approach 2: Using filter() method

We can filter all the element which is unique by using the filter() method. Then we will make one new array in which we concat our filtered array.

Example:




let arr1 = [54, 71, 58, 95, 20];
let arr2 = [71, 51, 54, 33, 80];
 
let unique1 = arr1.filter((o) =>
              arr2.indexOf(o) === -1);
let unique2 = arr2.filter((o) =>
              arr1.indexOf(o) === -1);
 
const unique = unique1.concat(unique2);
console.log(unique);

Output
[ 58, 95, 20, 51, 33, 80 ]

Article Tags :