Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptGet the Difference between Two Sets using JavaScript

Get the Difference between Two Sets using JavaScript

Given two Sets and the task is to compute the set difference between the two Sets using JavaScript. This means that the array we subtract should contain all the unique element which is not present in the second array.

We can get the difference between two sets using Javascript by the following methods:

Approach 1: Use the filter() method

  • Store both array values in the two variables.
  • Use the filter() method for every value of array_1, if there is a value in array_2 then do not include it. Otherwise include the value of array_1.

Example 1: In this example, the set difference is calculated using the filter() method

Javascript




let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
 
function GFG_Fun() {
    let diff = A.filter(x => !B.includes(x))
    console.log("Set-Difference: " + diff);
}
 
GFG_Fun();


Output

Set-Difference: 7,2,5


Example 2: In this example, the set difference is calculated using the filter() method but by a bit different approach. 

Javascript




A = ["GFG", "GeeksForGeeks", "a", "b"];
 B = ["gfg", "a", "b"];
 
function GFG_Fun() {
    diff = A.filter(function (x) {
        return B.indexOf(x) < 0
    })
 
    console.log("Set Difference: " + diff);
}
 
GFG_Fun();


Output

Set Difference: GFG,GeeksForGeeks


Approach 2: Using Set delete() Method

The Set.delete() method in JavaScript is used to delete an element with a specified value in a set and returns a boolean value depending upon the availability of the element.

Example:

Javascript




let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
const set1 = new Set(A);
const set2 = new Set(B);
 
const difference = new Set(set1);
for (const element of set2) {
    difference.delete(element);
}
console.log([...difference]);


Output

[ 7, 2, 5 ]

Approach 3: Using Set forEach() Method

The set.forEach() method is used to execute the function which is taken as a parameter and applied for each value in the set, in insertion order.

Example:

Javascript




let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
const set1 = new Set(A);
const set2 = new Set(B);
 
const difference = new Set();
set1.forEach(element => {
    if (!set2.has(element)) {
        difference.add(element);
    }
});
console.log([...difference]);


Output

[ 7, 2, 5 ]

RELATED ARTICLES

Most Popular

Recent Comments