JavaScript(JS) JS illustrate different set operations

www‮‬.theitroad.com

In JavaScript, you can use the built-in Set object to perform various set operations. Here are some examples of common set operations:

  1. Union: Combine two sets and remove any duplicates
let set1 = new Set([1, 2, 3]);
let set2 = new Set([2, 3, 4]);

let unionSet = new Set([...set1, ...set2]);

console.log(unionSet); // Output: Set {1, 2, 3, 4}
  1. Intersection: Find the elements that two sets have in common
let set1 = new Set([1, 2, 3]);
let set2 = new Set([2, 3, 4]);

let intersectionSet = new Set([...set1].filter(x => set2.has(x)));

console.log(intersectionSet); // Output: Set {2, 3}
  1. Difference: Find the elements that are in one set but not the other
let set1 = new Set([1, 2, 3]);
let set2 = new Set([2, 3, 4]);

let differenceSet = new Set([...set1].filter(x => !set2.has(x)));

console.log(differenceSet); // Output: Set {1}
  1. Subset: Check if one set is a subset of another set
let set1 = new Set([1, 2, 3]);
let set2 = new Set([1, 2, 3, 4]);

let isSubset = [...set1].every(x => set2.has(x));

console.log(isSubset); // Output: true

In these examples, we create two sets (set1 and set2) and perform various set operations on them using the Set object and other built-in functions like filter() and every(). The resulting sets are printed to the console using console.log().

The first example shows the union of the two sets, which combines all the elements from both sets and removes any duplicates. The second example shows the intersection of the two sets, which finds the elements that are in both sets. The third example shows the difference of the two sets, which finds the elements that are in one set but not the other. The fourth example shows how to check if one set is a subset of another set.