Skip to content

JavaScript Set difference

  • by

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:

  1. Convert the first Set to an Array.
  2. Use the filter() method to iterate over the array.
  3. Use the has() method to check if each element is not contained in the second Set.
  4. 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:

JavaScript Set difference

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

Leave a Reply

Your email address will not be published. Required fields are marked *