Skip to content
Related Articles

Related Articles

Improve Article

How to find every element that exists in any of two given arrays once using JavaScript ?

  • Last Updated : 01 Apr, 2021

In this article, we will learn how to find every element that exists in any of the given two arrays.

Method 1: Using set

A set is a collection of items that are unique i.e. no element can be repeated. We will add all elements of two arrays to the set, and then we will return the set.

Example: 

const arr1 = [1, 2, 3, 4, 5]
const arr2 = [1, 2, 3, 4, 5, 6]



result = [1, 2, 3, 4, 5, 6]

Code Example:

Javascript




<script>
  
    // Javascript program to find all element
    // present in any of two given arrays
  
    // Function which takes an array as argument
    const print = (arr1,arr2) => {
  
        // Creating a set with elements of arr1
        const set = new Set(arr1)
  
        // Adding elements of arr2
        arr2.forEach(element => {
            set.add(element)
        });
  
        // Returning resultant array
        return set
    }
  
    // Input array
    const arr1 = [10, 20, 30, 40, 50]
    const arr2 = [10,20,34,32,11]
       
    // Printing the result
    console.log(print(arr1,arr2))
</script>

Output:

{10, 20, 30, 40, 50, 34, 32, 11}

Method 2: Using loop

In this approach, we will choose one array and then we will run a loop on the second array and check whether an element of this array is present in the first array or not. If an element is already present, we skip otherwise we will add this to the first array.

Code Example:

Javascript




<script>
    // Javascript program to find all element
    // present in any of two given arrays
  
    // Function which takes an array as argument
    const print = (arr, arr2) => {
  
        // A counter for adding element
        let k = arr.length
  
        // Checking every element and
        // adding required element
        arr2.forEach(element => {
            if (arr.indexOf(element) == -1) {
                arr[k] = element
                k++
            }
        });
  
        // Returning resultant array
        return arr
    }
  
    // Input array
    const arr1 = [1, 2, 3, 4, 5]
    const arr2 = [1, 2, 3, 4]
  
    // Printing the result
    console.log(print(arr1, arr2))
</script>

Output:

[1, 2, 3, 4, 5]



My Personal Notes arrow_drop_up
Recommended Articles
Page :