DEV Community

Cover image for JavaScript Set
Bello Osagie
Bello Osagie

Posted on • Updated on

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


Top comments (0)