Search

New JavaScript Set methods

Sets in JavaScript are quite useful as they are like an array, but can only contain one of a specific item. So you can unique-ify an array easily, and even willy-nilly add stuff to it and not worry about duplicates:

const people = ["chris", "chris", "cindy"];
const peopleSet = new Set(people);
peopleSet.add("chris");
console.log(peopleSet);
// {"chris","cindy"}Code language: JavaScript (javascript)

Now they are even more useful with recently universally available methods, as Brian Smith summarizes:

  • intersection() returns a new set with elements in both this set and the given set.
  • union() returns a new set with all elements in this set and the given set.
  • difference() returns a new set with elements in this set but not in the given set.
  • symmetricDifference() returns a new set with elements in either set, but not in both.
  • isSubsetOf() returns a boolean indicating if all elements of a set are in a specific set.
  • isSupersetOf() returns a boolean indicating if all elements of a set are in a specific set.
  • isDisjointFrom() returns a boolean indicating if this set has no elements in common with a specific set.

It's time to take your JavaScript to the next level

Frontend Masters logo

Frontend Masters is the best place on the web to really learn JavaScript. We have a complete learning path from the biggest and best teachers in JavaScript to help you make the most out of the web's biggest language.

Leave a Reply

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