DEV Community

Mohammed Ali
Mohammed Ali

Posted on

Sets

  • Before ES6, JS had only two inbuilt Data Structures namely arrays & objects. ES6 introduced two new DS: Sets, Map.
  • For storage & orderly retirieveal use arrays.
  • Use sets only if order doesn't matter, and you just need to check the presence of element inside the data structure.
  • Sets are not intended to replace arrays. Arrays are more important.

- Whenever values need to be stored in order along with duplicates, arrays have to be used.

## Usecase: To remove duplicate values of arrays.
const order = ['pizza','burger','pasta','noodles','pizza','noodles','burger'];

const items = new Set(order);
items; // All duplicate values are removed

const city = new Set("California").size;
city; // 8
Enter fullscreen mode Exit fullscreen mode

Sets:

  • Sets are also iterables like String.
  • Collection of unique values.
const city = new Set("California");
city;     // Set(8) { 'C', 'a', 'l', 'i', 'f', 'o', 'r', 'n' }

Enter fullscreen mode Exit fullscreen mode
## Difference between Set & Array:
1. Although looks similar to array, but it has no key-value pairs. Hence, set[0] is invalid.
2. Only a list of unique values, all duplicate removed.
3. Order of element is irrelevant

## Similarities between Arrays & Sets:
1. Set has size property, Array has length propery.
2. Set has 'has' method, Array has includes method.

const order = ['pizza','burger','pasta','noodles','pizza','noodles','burger'];

const items = new Set(order);
items; // Set(4) { 'pizza', 'burger', 'pasta', 'noodles' }


//Both array and sets are iterables. Hence easier to convert from sets to array.
[...items];
Enter fullscreen mode Exit fullscreen mode

Adv: Can never have duplicate, although can hold mixed data types.
Most common iterable is Array. Ex. Syntax: new Set(iterable)

List of methods & properties on Sets:

.size;  // returns a numerical value
.has('name'); // returns a boolean value
.add('name');  // returns the set with added value
.delete('name'); // returns a boolean value
.clear(); // deletes all elements. returns Set(0) {} 


Enter fullscreen mode Exit fullscreen mode

Top comments (0)