How to use Set In Javascript
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.
// 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 }
How to find every element that exists in any of two given arrays once using JavaScript ?
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.
Table of Content
- Using Set
- Using loop
- Using filter() and concat()
- Using reduce and includes