JavaScript set Difference (a \ b): create a set that contains those elements of a set a that are not in a set b
. This operation is also sometimes called minus (-
).
function getDifference(setA, setB) {
return new Set(
[...setA].filter(element => !setB.has(element))
);
}
To get the difference between two Sets:
- Convert the first
Set
to an Array. - Use the
filter()
method to iterate over the array. - Use the
has()
method to check if each element is not contained in the secondSet
. - Convert the array back to a
Set
.
JavaScript Set difference
Simple example code computes a set difference using Javascript arrays.
<!DOCTYPE html>
<html>
<body>
<script>
var A = [1, 2, 3, 4, 8];
var B = [1, 3, 4, 7, 5];
var diff = A.filter(function(x) {
return B.indexOf(x) < 0;
});
console.log(diff);
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this set topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version