how to get the difference of two sets in javascript

To get the difference of two sets in JavaScript, you can use the Set object along with the spread operator and the filter method.

Here's an example code:

index.tsx
const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([2, 3, 5, 6]);

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

console.log(difference);
// Output: Set { 1, 4 }
188 chars
8 lines

In the code above, we first create two sets set1 and set2 with some values. We then use the spread operator ... to convert set1 into an array and pass it into the filter method.

In the filter method, we pass a callback function that checks if the current value x of the array is not present in set2. If it's not present, the filter method returns true and includes x in the new set difference.

Finally, we log the difference set to the console, which should output Set { 1, 4 }.

gistlibby LogSnag