A Set data structure allows to add data to a container, a collection of objects or primitive types (strings, numbers or booleans), and you can think of it as a Map where values are used as map keys, with the map value always being a boolean true.

  • What is a Set
  • Initialize a Set
    • Add items to a Set
    • Check if an item is in the set
    • Delete an item from a Set by key
    • Determine the number of items in a Set
    • Delete all items from a Set
  • Iterate the items in a Set
  • Initialize a Set with values
  • Convert to array
    • Convert the Set keys into an array
  • A WeakSet

What is a Set

A Set data structure allows to add data to a container.

ECMAScript 6 (also called ES2015) introduced the Set data structure to the JavaScript world, along with Map

A Set is a collection of objects or primitive types (strings, numbers or booleans), and you can think of it as a Map where values are used as map keys, with the map value always being a boolean true.

Initialize a Set

A Set is initialized by calling:

const s = new Set()

Add items to a Set

You can add items to the Set by using the add method:

s.add('one')
s.add('two')

A set only stores unique elements, so calling s.add('one') multiple times won’t add new items.

You can’t add multiple elements to a set at the same time. You need to call add() multiple times.

Check if an item is in the set

Once an element is in the set, we can check if the set contains it:

s.has('one') //true
s.has('three') //false

#javascript #programming #web-development #developer

The Set JavaScript Data Structure
1.85 GEEK