Sets

Contact Us or call 1-877-932-8228
Sets

Sets

Another useful JavaScript object is the Set. Unlike a Map, a Set object can contain no duplicate items: it stores only unique values, of any type. As with Maps, we can iterate over a Set object in insertion order.

Common Set Properties
Property Description Example
constructor Creates a Set theSet = new Set()
size Returns the number of values theSet.size
Common Set Methods
Method Description Example
add Appends a new value, if the value does not already exist in the set theSet.add('abc')
clear Removes all values theSet.clear()
delete Removes a specified value theSet.delete('abc')
forEach Iterates over the Set theSet.forEach(function (item) { //do something with each item })
has Returns true if is element is contained in the set theSet.has(20) // returns true if 20 exists in theSet

We'll take a look now at an example:

Code Sample:

AdvancedObjects/Demos/set.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Set</title>
</head>
<body>
	<h1>Set</h1>
	<script>
		var mySet = new Set();
		mySet.add(1);
		mySet.add("lemonade");
		var arr = ['one', 'two', 'three'];
		mySet.add(arr);
		mySet.add(1); // won't be added, as 1 already exists as an element

		document.write('<p>Size of set: ' + mySet.size + '</p>');
		document.write('<p>Does mySet have element 1?: ' + mySet.has(1) + '</p>');
		document.write('<p>Does mySet have element arr?: ' + mySet.has(arr) + '</p>');
		document.write('<p>Does mySet have element "blue?: ' + mySet.has("blue") + '</p>');
		mySet.clear();
		document.write('<p>(mySet cleared)</p>');
		document.write('<p>Size of set: ' + mySet.size + '</p>');
	</script>
</body>
</html>

Code Explanation

We create a new Set on line 10 and add values to it with the add method. Note that adding the value 1 on line 15 has no effect, since 1 was already added previously.

Next, we'll ask you to try out using Map and Set in the following exercise:

Next