DEV Community

Rakesh Patel
Rakesh Patel

Posted on

Set Data Structure in JavaScript

Map, WeakMap, Set and WeakSet these 4 are new Data structure which was introduced in ES6.

Before diving deep into these DS, let's first understand What is DS?

Data structures, at a high level, are techniques for storing and organizing data that make it easier to modify, navigate, and access.

Data structures are like container, which hold data ( primitive, object, etc.) and these container's have their own constraint/rule/pattern to access, modify, delete their data.

DS are not limited to particular programming language only. Data structures are used in almost all areas of computer science and programming, from operating systems to basic vanilla code to artificial intelligence.

Now, let's come to our topic,

Before Set & Map, JavaScript only have inbuild Array and Object DS. but in some scenarios this both not perform well and we needed to manually add extra functionality for getting things done. and therefore this new DS are introduced.

1. Set

Set DS hold only unique data. so Set guaranteed of no data is duplicated.

E.g.
Set Demo

  1. In above example, we have passed array of duplicate values to Set constructor but when we logged Set value, it returned only object with unique value's

Note : Set is object type not array type. that's why return value is object.

  1. In above example, I used shortcut way of initialization of Set via array. click here to read more detailed information of Set

  2. Set are implemented with Iterator protocol [Symbol.iterator] that means Set are by default Iterable object. so we can iterate the Set value with for...of loop

Iterating Set

Advantage's of Set over Array

  • Set hold only unique data (no duplicate value are allowed)
  • Time Complexity of searching element in Set is constant i.e. O(1). where as in Array it's linear i.e. O(n).

Real time Application

  • Suppose you have user list. where some user's name are repeated. then with the help of Set you can easily remove duplicate name

username demo

  • Searching for particular user name in huge list ( e.g. 5_00_000 records) because with array it take time O(n) complexity. but with Set we can quickly find user name

Time complexity
(output in time may varies machine to machine)

Refernces :

  1. https://exploringjs.com/es6/ch_maps-sets.html
  2. https://www.freecodecamp.org/news/how-to-use-javascript-collections-map-and-set/

Top comments (0)