New JavaScript Set Methods

2024-06-243:049238developer.mozilla.org

New JavaScript Set methods are landing across browsers. Learn about sets, how you can use these methods to compare different sets, create new sets with specific properties, and more.

A set is similar to an Array, except that each value can only be stored once. For example, we can take a list of items, add them all to a set, and then inspect the results of the set. The list on the right is the contents of the <ol> list on the left, but converted to a set. We have all duplicates removed from the list because we're guaranteed that a set is unique:

This might not look like much in a small example such as this, but it's really convenient to have a built-in way to make unique collections of items, especially over larger data and more complex data types and objects. For example, consider that you can add elements to a set like so:

const dogs = new Set();
const yoshi = { name: "Yoshi", personality: "Friendly" };
dogs.add(yoshi);

It's also typically faster to check if an element is in a set as opposed to in an Array, so this fits use cases where you need to keep an eye on performance in larger data sets. You can also compose new sets with specific logical properties based on existing sets, and we'll take a look at some examples of that below.

We'll be covering all of the new methods below, but if you want to see everything you can do with a Set, check the Instance methods documentation.


Read the original article

Comments

  • By esprehn 2024-06-252:32

    I'm very excited this finally shipped everywhere! Prior to this Set wasn't much more than a Map<any, true> since it had no actual Set operations.

  • By mcphage 2024-06-2417:00

    Oh, that's a relief. Having "set" objects in JS, without having any of the standard set operations, didn't make a lot of sense.

  • By bsmth 2024-06-247:271 reply

    Blog post author here in case there's any feedback or questions. Thanks for sharing :)

    • By dmix 2024-06-2416:041 reply

      Thanks for the post. One thing, I wanted to test this in chrome and I realized your examples are all based on a larger Playground with a test HTML doc.

      Maybe one self-contained example w/ a new function you can copy/paste into the console to play around with would be cool.

      I was mostly using it as a test to see if it worked in Chrome so I could start using it.

      • By bsmth 2024-06-2421:00

        That's a good idea. I'll have a think about a JS only example, although the reference pages have some, they log results to the console and so I thought some HTML might be interesting to see.

        Maybe it's interesting for you: the method pages have compat data at the bottom so you can see what's supported and in which browser release.

HackerNews