What Is the Difference Between a Set and an Array ?
Problem
In what situation would you use a set object over an array?
Solution
There are some similarities between the two objects. They can both hold on to data of different types. What separates a set is that the values all need to be unique.
The Code
var numberSet = new Set();
numberSet.add(1);
numberSet.add(2);
numberSet.add(3);
numberSet.add(3); //does not get added
console.log(numberSet.entries()); //returns SetIterator {[1, 1], [2, 2], [3, 3]}
var numArray = new Array();
numArray.push(1);
numArray.push(2);
numArray.push(3);
numArray.push(3);
console.log(numArray); //returns [1, 2, 3, 3]
Listing 10-1.
Showing the Difference Between Sets and Arrays
How It Works
Some of the properties and methods associated with a set are very similar to what you would find with an array. For example, the size property is like using the length property
in an array. Where arrays can have multiple elements with the same value, sets are made to contain unique values for each element.
How Do You Add and Remove Elements of a Set ?
Problem
You need to manage elements of a set.
Solution
An array uses push to add elements, whereas sets use the add method. To remove elements, use the delete method.
The Code
var numberSet = new Set();
numberSet.add(1);
numberSet.add(2);
numberSet.add(3);
numberSet.add('things');
console.log(numberSet.size); //returns 4
numberSet.delete('things');
console.log(numberSet.size); //returns 3
Listing 10-2.
Adding and Removing Elements from a Set Object
How It Works
If you wanted to remove the last element of an array, you can use the pop method. If you know the index number, you can use the splice method. With sets, you can use the delete method and pass the value of the element you want to delete. Use the add method like in Listing 10-2 to add elements.
How Do You Remove All the Elements of a Set?
Problem
You need to remove all elements of a set object.
Solution
The
clear method
will remove all elements from a set, whereas delete will only remove one.
The Code
var numberSet = new Set();
numberSet.add(1);
numberSet.add(2);
numberSet.add(3);
numberSet.add('things');
console.log(numberSet.size); //returns 4
numberSet.clear();
console.log(numberSet.size); //returns 0
Listing 10-3.
Removing All Elements from a Set Object
How It Works
There are a few ways of removing items from an array. Sets make it easy with the clear method. In the example in Listing 10-3, clear will remove all existing elements from the set.
What Is the Difference Between the Keys and Values Methods ?
Problem
You need to know when to use the keys method over the values method.
Solution
Both methods return an iterator object that contains values for each element. The keys method is an alias for the values method.
The Code
var numberSet = new Set();
numberSet.add(1);
numberSet.add(2);
numberSet.add(3);
numberSet.add('things');
console.log(numberSet.keys()); //returns SetIterator {1, 2, 3, "things"}
console.log(numberSet.values()); //returns SetIterator {1, 2, 3, "things"}
var elements = numberSet.values();
console.log(elements.next().value); //returns 1
console.log(elements.next().value); //returns 2
Listing 10-4.
Checking If a Value Exists in a Set
How It Works
The values and keys methods both return an iterator object
. If you want to manually see the next element, you can use the next method.
How Many Elements Are in the Current Set?
Problem
You want to know the number of elements in a current set.
Solution
Use the
size property
to determine how many elements are in a set object.
The Code
var numberSet = new Set();
numberSet.add(1);
numberSet.add(2);
numberSet.add(3);
numberSet.add('things');
console.log(numberSet.size); //returns 4
Listing 10-5.
Using Size to Determine How Many Elements Are in a Set
How It Works
The size property
returns an integer letting you know how many elements are in the set. Unlike with an array, this property cannot be set.
What Is a WeakSet ?
Problem
You need to know the difference between a set and a WeakSet.
Solution
WeakSets only hold on to objects, where a set can hold on to items of any type. References to objects in the collection are garbage collected if there are no references to them.
The Code
var weakSet = new WeakSet();
var obj1 = {};
weakSet.add(obj1);
console.log(weakSet.has(obj1)); //returns true just like a Set
Listing 10-6.
WeakSets Work in a Similar Way to Sets
How It Works
The methods of a weakSet are the same as a set object. The main difference between the two is that only objects can be saved as elements. WeakSets are also not enumerable
and are garbage collected if there are no references to objects in the weakSet.
How Does a forEach Method Work with a Set Object?
Problem
You need to know if there a difference using a forEach method on a set versus an array.
Solution
The forEach method works the same when using a set as when using an array. The method is called for each value in the set.
The Code
var numberSet = new Set();
numberSet.add(1);
numberSet.add(2);
numberSet.add(3);
numberSet.forEach(function(value){
console.log(value); //returns 1,2,3
});
Listing 10-7.
Looping Through a Set Using the forEach Method
How It Works
In order to be consistent with the map and array versions, the
forEach method
will be called once for each element in a set. When the function is called, three arguments are sent over. The first two will be the value of the element. The third would have been the set object that is being transversed.
Can You Check If an Element Exists in a Set?
Problem
You want to know if an element with a certain value exists in the set.
Solution
The
has method
will return a Boolean based on if there is an element with the given value inside the set.
The Code
var bandSet = new Set();
bandSet.add('Dave');
bandSet.add('Martin');
bandSet.add('Fletch');
console.log(bandSet.has('vince')); //returns false
console.log(bandSet.has('Dave')); //returns true
Listing 10-8.
Determining If Any Element in the Set Has a Certain Value
How It Works
The
has method
is similar to the find method in an array, in that you can search for the value in an array. The has method does not require a callback function. It simply returns a value of true or false if there is any element in the set that contains the given value.
Can a Set Generate Iterator Objects?
Problem
You want to customize how you iterate through a set.
Solution
The
entries method
will return an array of each element in the order of insertion.
The Code
var bandSet = new Set();
bandSet.add('Dave');
bandSet.add('Martin');
bandSet.add('Fletch');
bandSet.add('Jim');
bandSet.add('Paul');
bandSet.add('Kurt');
bandSet.add('Andy');
bandSet.add('Vince');
var entry = bandSet.entries();
console.log(entry.next().value); //returns ["Dave", "Dave"]
console.log(entry.next()); //returns Object {value: Array[2], done: false}
while(entry.next().done == false){ //as long as the current item returns false then keep going
console.log(entry.next().value)
}
Listing 10-9.
Creating a Custom Iterator with a Set
How It Works
When using the
entries method
, you can create a custom iterator for the set. (For more information about iterators, see Chapter 13.) The iterator object contains two properties, done and value. Sets do not have keys in the same way that a map does. Because of this, it returns the same value as both the key and the value. This keeps the API similar to the Map object.
The
done property
returns a Boolean letting you know if you have reached the last item in sequence. The value is false until the last item has been reached.
The
value property
returns an array. Because set objects do not have a key, the value of both items in the array are the same. This keeps it consistent with the Map object.