Ionut Andrei Dirlea

Sets

May 27, 2019 - 1 min read
Personal blog of Ionut Andrei Dirlea
I write about JavaScript, React, Swift, Swift UI and love of coding

Sets it's an object type that was introduced in ES6 that allows to create unique collections of items. The items can be primitive values like numbers and strings, but also more complex types like objects or arrays.

Let's see how can we create a set and some of the useful methods of a set object.

const cars = new Set();

// adding a primitive value
cars.add('Audi')

// adding an object
cars.add({ type: 'automobile', make: 'bmw'})

// adding an array
cars.add(['dacia', 'ford'])

// checking the size of the set
console.log(cars.size) // 3

// checking an element that exists
console.log(cars.has('Audi')) // true

// delete an item
cars.delete('audi')
console.log(cars.size) // 2

We can also initialise a set from an array.
const animals = new Set(['pig', 'cow', 'dog', 'cat', 'horse', 'pig']);

// the set will contain only the unique items
console.log(animals.size) // 5

// iterating over a set
animals.forEach((animal) => {
	console.log(animal)
});

pig
cow
dog
cat
horse

Another application of sets is to retrieve unique characters from a sentence

const string = 'Here we are learning about sets';
console.log(string.length) // 31

const sentence = new Set(string)
console.log(sentence.size) // 15

Sets have also the keys and values methods. The keys method is an alias for the values method. Using either of them will do the same thing. For example calling the values method will return an new iterator object with the values of the set in the same order they were added. Let's see an example:

const animals = new Set(['pig', 'cow', 'dog']);
const items = animals.values();

console.log(items.next());
console.log(items.next());
console.log(items.next());
console.log(items.next().done);
{ done: false, value: 'pig' }
{ done: false, value: 'cow' }
{ done: false, value: 'dog' }
false

That is all you need to know about sets at the moment.