Open In App

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

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

In this article, we will learn how to find every element that exists in any of the given two arrays. To find every element that exists in any of two given arrays, you can merge the arrays and remove any duplicate elements.

Method 1: Using Set

A set is a collection of unique items 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: In this example, we will see the use of the Javascript set method to find every element that exists in any of the two given arrays once.

Javascript




// 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))


Output

Set(8) { 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.

Example: In this example, we will see the use of Javascript loops to find every element that exists in any of the two given arrays once.

Javascript




// 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))


Output

[ 1, 2, 3, 4, 5 ]



Method 3: Using filter() and concat()

In this method, we will use the concat() method to merge the array and filter() method for removing the element which repeats.

Example:

Javascript




function findElementsInArr(arr1, arr2) {
    let mergedArray = arr1.concat(arr2);
    let uniqueEle = mergedArray.filter(function (element, index, self) {
        return self.indexOf(element) === index;
    });
    return uniqueEle;
}
 
let arr1 = [1, 2, 3, 4];
let arr2 = [3, 4, 5, 6];
let result = findElementsInArr(arr1, arr2);
console.log(result);


Output

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





Similar Reads

JavaScript Program to Find Element that Appears once in Array where Other Elements Appears Twice
Given an Array of Integers consisting of n elements where each element appears twice except one element. The task is to find the element which appears only once in the input array in JavaScript. Example: Input : arr = [ 5, 9, 2, 7, 4, 8, 6, 1, 5, 1, 4, 6, 3, 7, 8, 2, 9 ] Output : 3Explanation: The input array consists of 17 elements where all eleme
2 min read
How to find if two arrays contain any common item in Javascript ?
JavaScript Array is a single variable that is used to store elements of different data types. JavaScript arrays are zero-indexed. So, we are given two arrays containing array elements and the task is to check if two arrays contain any common elements then it returns True otherwise returns False. These are the following ways to solve this problem: T
4 min read
Top 10 Tools That Every Web Developer Must Try Once
If you want to do any task easily, effectively, and efficiently then you should use some tools. Though there are lots of different software development tools available. You have to select the most useful tools depending on the requirement and technology that you are working on. A good programmer should know which tools are better than others and al
6 min read
JavaScript Program to Find Kth Element of Two Sorted Arrays using Binary Search
Given two sorted arrays, our task is to find the Kth element in the combined array made by merging the two input arrays using Binary Search in JavaScript. Example: Input: Arr1: [1, 2, 5] , Arr2:[2, 4, 6, 8], K = 4Output: Kth element is 4.Explanation:The final Array would be: [1, 2, 2, 4, 5, 6, 8]The 4th element of this array is 4.ApproachInitialize
2 min read
How to attach an event to an element which should be executed only once in JavaScript ?
In this article, we will learn how to attach an event to an element which should be executed only once. There are two approaches that can be used here: Approach 1: In this approach, we will be using the jQuery one() method. This method attaches an event to the element with the specified selector. It is named one because the event handler correspond
3 min read
PHP Program for Find the element that appears once
Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once. Expected time complexity is O(n) and O(1) extra space. Examples : Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3} Output: 2 In the given array all element appear three times except 2 which appears once. Input: arr[]
3 min read
How to Check an Element with Specific ID Exists using JavaScript ?
Given an HTML document containing some elements and the elements contain some id attribute. The task is to check whether the element with a specific ID exists or not using JavaScript. There are two approaches that are discussed below:  Table of Content Using document.getElementById() methodUsing document.getElementById() and JSON.stringify() method
2 min read
How to reload page only once in JavaScript ?
In this article, we are going to implement a JavaScript code that would allow us to reload a page only once. The Simplest implementation: window.location.reload() It is the simplest inbuilt method in JavaScript that will reload the page, but the task is to refresh the page/reload the page only once. As this JavaScript method reloads the page repeat
2 min read
Function that can be called only once in JavaScript
In JavaScript, you can create a function that can be called only once by using a closure to keep track of whether the function has been called before. JavaScript closure is a feature that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer boundary and is created automatically whenever a
3 min read
Check if Pair with given Sum Exists in Array using JavaScript
We will check if a pair with a given Sum exists in an Array or not using JavaScript. 2Sum ProblemThe 2sum is a famous problem asked in most interviews. We have to check whether a pair of numbers exists whose sum is equal to the target value. We are given an array of integers and the target value. We have to return true if the pair whose sum is equa
4 min read