Open In App

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

Last Updated : 11 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Create an empty array that would store the unique elements from the two arrays.
  • Iterate over all elements of array1 using a loop.
  • Set the initial flag value as 0 for each iteration.
  • In that loop Iterate over all elements of array2 using another loop and check if array1[element] is present in array2.
  • If present, remove the element from array2 using the splice() method and set the flag to 1.
  • If array2 has been fully traversed for array1[element] and the flag is still equal to 0, add the array1[element] to the unique elements array.
  • Repeat steps 4-6 for each element in array 1.
  • Finally, push array2 to the unique elements array since all duplicate elements have been removed from array2 (refer to Step 5).

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

Javascript




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:

Javascript




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 ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads