
New Javascript Set methods
What is a JavaScript Set?
A JavaScript Set is an array with unique items. An item cannot be in the array more than once. Besides the regular "Set" methods like "add", "clear", and "delete", there are a few new, useful methods.
The new methods
intersection() - returns a new set with elements in both this set and the given set.
const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.intersection(squares)); // Set(2) { 1, 9 }union() - returns a new set with all elements in this set and the given set.
const fruits = new Set(['banana', 'apple, 'watermelon']);
const vegetables = new Set(['cucumber', 'eggplant']);
console.log(fruits.union(vegetables )); // Set(5) { 'banana', 'apple, 'watermelon', 'cucumber', 'eggplant' }difference() - returns a new set with elements in this set but not in the given set.
const odds = new Set([1, 3, 5, 7, 9]);
const squares = new Set([1, 4, 9]);
console.log(odds.difference(squares)); // Set(3) { 3, 5, 7 }symmetricDifference() - returns a new set with elements in either set, but not in both.
const evens = new Set([2, 4, 6, 8]);
const squares = new Set([1, 4, 9]);
console.log(evens.symmetricDifference(squares)); // Set(5) { 2, 6, 8, 1, 9 }isSubsetOf() - returns a boolean indicating if all elements of this set are in the given set.
const fours = new Set([4, 8, 12, 16]);
const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
console.log(fours.isSubsetOf(evens)); // true
const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const odds = new Set([3, 5, 7, 9, 11, 13, 15, 17, 19]);
console.log(primes.isSubsetOf(odds)); // falseisSupersetOf() - returns a boolean indicating if all elements of the given set are in this set.
const evens = new Set([2, 4, 6, 8, 10, 12, 14, 16, 18]);
const fours = new Set([4, 8, 12, 16]);
console.log(evens.isSupersetOf(fours)); // true
const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const odds = new Set([3, 5, 7, 9, 11, 13, 15, 17, 19]);
console.log(odds.isSupersetOf(primes)); // falseisDisjointFrom() - returns a boolean indicating if this set has no elements in common with a specific set.
const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19]);
const squares = new Set([1, 4, 9, 16]);
console.log(primes.isDisjointFrom(squares)); // true
const composites = new Set([4, 6, 8, 9, 10, 12, 14, 15, 16, 18]);
const squares = new Set([1, 4, 9, 16]);
console.log(composites.isDisjointFrom(squares)); // falseSummary
Using a JavaScript Set is a good practice when you want to keep a unique array of items and easily manipulate the data with methods like the one above, as well as other methods that make it easy to do so.