Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 14 Sep, 2020

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

Approach:

  • 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 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 array1.
  • Finally, push array2 to the unique elements array since all duplicate elements have been removed from array2 (refer Step 5).

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

Javascript




<script>
function unique(arr1,arr2,uniqueArr) {
    for(var i=0; i<arr1.length; i++) {
        flag = 0;
        for(var 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;
}
  
var arr1 = [54, 71, 58, 95, 20];
  
var arr2 = [71, 51, 54, 33, 80];
  
var uniqueArr = [];
  
console.log("Unique elements in the two arrays are:");
console.log(unique(arr1,arr2,uniqueArr).flat());
</script>

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :