DEV Community

Cover image for JavaScript Set
Bello Osagie
Bello Osagie

Posted on • Edited on

1

JavaScript Set

A Set is a collection of a set of values without keys.

The common methods and properties are shown below:

  • new Set(iterable) – creates the set, and if an iterable object (eg. array)
  • set.add(value) – adds a value
  • set.delete(value) – removes the value
  • set.has(value) – returns true if the value exists, otherwise false.
  • set.clear() – removes everything from the set.
  • set.size – returns the current element count.

Set calls

Repeated calls of the same set.add(value) don't count.

See the example below:

const set = new Set();

const bello = { name: 'Bello' };
const monica = { name: 'Monica' };
const jerry = { name: 'Jerry' };

set.add(bello);
set.add(monica);
set.add(monica);
set.add(jerry);
set.add(jerry);

console.log( set.size ); // 3

for (let user of set) {
  console.log(user.name);

/*
3
Bello
Monica
Jerry
*/
}
Enter fullscreen mode Exit fullscreen mode

The example above shows that Set prevents repetition of properties in an iterable object.

Let's filter out all repeating items in the array or prevent items from repeating more than once in the array.

See the example below:

const randomWords = [ 
  'pursue', 'admire', 'power', 'pursue', 
  'advocate', 'begin', 'admire', 'love', 'joyful' 
];

const uniqueRandomWords = [ ...new Set(randomWords) ];
console.log(uniqueRandomWords);

/*
[
  'pursue', 'admire',
  'power',  'advocate',
  'begin',  'love',
  'joyful'
]
*/
Enter fullscreen mode Exit fullscreen mode

Iteration over Map

There are 3 methods to loop over a set — the same methods are used on map.

  • set.keys() - returns an iterable for keys,
  • set.values() - returns an iterable for values,
  • set.entries() - returns an iterable for entries

See the example below:

const set = new Set([ 'Apple', 'Orange', 'Melon']);

// for...of
for (let value of set) { 
  console.log(value);

/*
Apple
Orange
Melon
*/

}

// forEach:
set.forEach((value, valueAgain, set) => {
  console.log(value);

/*
Apple
Orange
Melon
*/

});
Enter fullscreen mode Exit fullscreen mode

value and valueAgain are the same value for compatibility with Map

Happy coding!!!


Buy me a Coffee


Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay