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
const print = (arr1,arr2) => {
const set = new Set(arr1)
arr2.forEach(element => {
set.add(element)
});
return set
}
const arr1 = [10, 20, 30, 40, 50]
const arr2 = [10,20,34,32,11]
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
const print = (arr, arr2) => {
let k = arr.length
arr2.forEach(element => {
if (arr.indexOf(element) == -1) {
arr[k] = element
k++
}
});
return arr
}
const arr1 = [1, 2, 3, 4, 5]
const arr2 = [1, 2, 3, 4]
console.log(print(arr1, arr2))
|
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 ]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Jul, 2023
Like Article
Save Article