JavaScript Set Builtin Data Structure

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Set Builtin Data Structure

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Introduction

const numbers = new Set();
numbers.add(5); // Set { 5 }
numbers.add(1); // Set { 5, 1 }
numbers.add(5); // Set { 5, 1 }

const messages = new Set(['hola', 'mundo', 'hola']);
console.log(messages); // Set { 'hola', 'mundo' }

const characters = new Set('hello');
console.log(characters); // Set { 'h', 'e', 'l', 'o' }

console.log(numbers instanceof Set); // true
console.log(messages instanceof Set); // true
console.log(characters instanceof Set); // true

Iterable

const people = new Set(['John', 'Jane', 'Jack']);

for (const person of people) {
console.log(person); // John, Jane, Jack
}

const peopleArray = [...people];
console.log(peopleArray); // ['John', 'Jane', 'Jack']

const peopleCopy = new Set(people);
peopleCopy.add('Jill');
console.log(peopleCopy); // Set {'John', 'Jane', 'Jack', 'Jill'}
console.log(people); // Set {'John', 'Jane', 'Jack'}

Maintain Insertion Order

const orderOne = new Set(['Pizza', 'Ice Cream']);
const orderTwo = new Set(['Ice Cream', 'Pizza']);

const orderOneArray = [...orderOne]; // ['Pizza', 'Ice Cream']
const orderTwoArray = [...orderTwo]; // ['Ice Cream', 'Pizza']

const missedCalls = ['Jane', 'Jack', 'Jane', 'Jill'];
const uniqueMissedCalls = [...new Set(missedCalls)]; // ['Jane', 'Jack', 'Jill']

Methods and Properties

const spices = new Set(['nutmeg', 'ginger']);

spices.add('cumin'); // Set { 'nutmeg', 'ginger', 'cumin' }

spices.delete('ginger'); // true
spices.delete('ginger'); // false

spices.has('cumin'); // true
spices.has('ginger'); // false

console.log(spices); // Set { 'nutmeg', 'cumin' }
console.log(spices.size); // 2

spices.clear(); // Set {}
console.log(spices.size); // 0

Set Performance

const count = 10_000;
const input = [...Array(count)].map(
() =>
Math.floor(Math.random() * (count / 2))
);

console.time('array');
const array = [];
for (const item of input) {
if (array.indexOf(item) === -1) {
array.push(item);
}
}
console.timeEnd('array');

console.time('set');
const set = [...new Set(input)];
console.timeEnd('set');

console.log({
withArray: array.length,
withSet: set.length,
});

Example Interview Questions

const input = ['a', 'b', 'a', 'c'];

const removeDuplicates = (array) => [...new Set(array)];
console.log(removeDuplicates(input)); // ['a', 'b', 'c']

const hasDuplicates = (array) => new Set(array).size !== array.length;
console.log(hasDuplicates(input)); // true

const findRepeatedItems = (array) => {
const seen = new Set();
const repeated = new Set();
for (const item of array) {
if (!seen.has(item)) {
seen.add(item);
} else {
repeated.add(item);
}
}
return [...repeated];
};
console.log(findRepeatedItems(input)); // ['a']
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Having a proper O of one set data structure is critical for high performance computing, and it didn't get edited JavaScript till after JavaScript had already exploded in popularity. Fortunately, now that we have this built-in set class, it makes trivial work of a number of popular programming interview questions. We simply create a new instance of the set by using the set constructor With a new operator, A set has a number of features and we can add new items to the set by using the add function. So if we add five, the set has a single item, which is the number five. We can add another item, for example one, and now the set has two items, the number five and the number one.

00:36

A set only stores unique items internally. It does that by using hashing and sets can quickly see in constant time if a particular value already exists in the set. And if not, it adds that to the set. So if you add the number five to the set, it'll see that it already has five present within it and it will not add it again. This high performance lookup and deduplication is the key reason for the existence of the set data structure. In addition to adding ajas using the add method, we can also pass an attri to the constructor of the set and the set automatically adds all of those items by iterating over the input in the array

01:11

that we are passing. Right now, there are only two unique strings, Hola and Mundo, and those are the only two values that will be present within the set. Notice that the set constructor accepts any intervals, which means that in addition to erase, we can pass it. Anything else? For example, we know that within JavaScript strings are also BLEs, so we can even pass in a string if you wanted to. And of course it'll iterate over the different characters within the string and again, ensure that only unique values get added. Notice that within the string, hello, the character L appears twice, but it'll exist only once within the character set.

01:46

Just like any other J strip class, we can check if a particular value is an instance of the set class by using the instance of operator. And over here the values, numbers, messages and characters are all an instance of set. We've seen that the set data structure accepts Itals in the constructor, but what's worth noting is that the set itself is also an Iterable. Let's create a set that consists of three strings, John, Jane, and Jack. Because the set is an al, we can use it anywhere else. We can use an Iterable within JavaScript, for example, with a four off loop.

02:20

If you loop through the people set, we get back the individual strings, John, Jane, and Jack. Additionally, just like any other retriable, we can spread the set into a JavaScript array, and of course in this particular case, we will get back an array that contains the three strings that we put in the set because the set constructor accepts an retriable and the set itself is also retriable. It makes it a trivial task. To create a copy of a set, we can simply take a set and pass it to the set constructor to create a copy. Since people copy is a copy of the original set, any mutations that we make to the people copy will of course be only in the

02:56

people copy. So here we are adding Jill to The people copy, and of course it's present in people copy, but not present in the original people set. Little known fact particular to JavaScript and different from other programming languages is that the JavaScript set guarantees that it'll maintain insertion order. So if you create a set with the array pizza and ice cream, it'll have the items pizza and ice cream in that order. If however, we create a set with ice cream and then pizza, then again the order will be different and we can demonstrate this preservation of insertion order. If we convert the set back to an array,

03:31

the items will display in the order that they were added to in the original set. This is actually great because order is significant for arrays and it allows for an easy conversion of an array into a set to remove any duplications and then a conversion back to the array while preserving the order of the items. To demonstrate this, consider the example that we've received. Missed calls from Jane, then Jack, then Jane, and then Jill. We should only call back the individuals only once, however, we want to call them back in the order that they called us. So we really want to only call Jane once, then Jack and then Jill.

04:07

We can find the unique callers so that we can call them back in the correct order quite easily by simply taking the array, passing it through a set to only get the unique items and then converting it back to an array with a simple spread operator. So here we get the answer that we are looking for. We need to call back Jane, then Jack, and then Jill. And as an aside, we might not even need to call Jill because when we will call Jack, he'll probably tell us that they went up a hill. The JavaScript set is a pretty easy data structure to master because it only has a handful of properties and methods. We already know that the set constructor takes any intervals. For example, hey,

04:42

we are passing an array of the spices, nutmeg, and ginger, and we can add more items by using the ad method. And now we have the set that has nutmeg, ginger, and cummin. There is a method that is the opposite of add, and we can remove items from the set by using the delete method. This method also returns true if the item was present within the set. So now that we have deleted ginger, if you run it again this time it'll return false because ginger was no longer present. Within the set. Sets also come with a hazmat that tells you if an item is present within the set or not. For example, here the set does have cummin, however,

05:17

since we've removed ginger, ginger is not present within the spices. So right now the set only has two spices, which are not mag and cummin, and we can check how many items are present within the set by using the size property. Of course, since there are two items, size will be the numeric too. Sets also come with a clear method which removes all the items from the set. And of course, once the set is empty, the size will turn to zero. Let's run through a simple example to prove that using the set at a structure is truly more performant than raw arrays and get some understanding of how stark the difference really is between o n for sets and O F N for arrays,

05:55

let's consider the simple task of removing duplicates from a given input array. To start off, we will create an array that will consist of 10,000 items. We create an array of 10,000 items and ensure that there will be some duplicates around half of them by creating numbers that will be in the range, zero to 10,000 divided by two. Let's measure the time of removing the duplicates from this input first by using just plain arrays and then by using sets with arrays, we create an output array and then simply loop to the input items. And each time we check if it is not already present within the array by using

06:31

index off. And if index office minus one meaning that the item is not already in the array, then we simply push it into the end of the output. We are going to time it using JavaScript built-in methods console dot time and console dot time end. Now let's repeat the same process, but this time by using a set. And as we know, we can remove duplicates from an input array by simply creating a set from that array and then converting that set back to an array by using the spread operator. If our algorithm is correct, then the result of using an array and the result of using the set should result in the same number of items.

07:05

So we will simply log out the length of the array output as well as the length of the set output. And now for the moment of truth, let's run this code to see what are the results from the array versus the results from the set. As we can see, they both contain the same number of items. However, the array took around 11 milliseconds and the set was done within one millisecond. Now with 10,000 items, even though the time difference is still quite large, 11 milliseconds doesn't feel like a big deal, so let's just bump it up to a hundred thousand. You can take a moment to guess how much of a difference it'll have because every

07:39

time we add a new item, the array has to look at all the existing items. The difference will be quite significant if you run the code. You can see in the output that the array takes around one second, whereas the set is still done within four milliseconds. The difference between a second and four milliseconds is the difference between a responsive and an unresponsive application. The key motivation for using the set at a structure is its O one item edition and lookup, and this has a number of real world high performance use cases like removing duplicates and finding repeated items. To demonstrate some applications,

08:14

we create a simple array that has characters A, B, and C where A is duplicated. We can create a utility method that removes duplicates from a given input array and all that it needs to do is to pass that array through a set and then return that BLE back into an array. And of course for our input example, we get back the strings A, B, and C. We can also easily create a utility method to check if a given input array has duplicates by simply passing that array through a set and checking if the size of the set is equal to the input array length. Of course, for our particular example, it does have duplicates,

08:49

and indeed when we pass it through the has duplicates function, we get back the boo true. In addition to removing duplicates, we can also use sets for finding the repeated items within a given input. We create two sets, one for the items that we have already seen and one for the items that we have found are indeed repeated. Then we simply look through the input and if we have never seen this item before, we added to the scene array. Otherwise, if we have seen it, then of course it is a repeated item and we add it to the repeated set. Once the loop terminates,

09:20

all our repeated items will be in the repeated set and we can convert that back into an array by using the spread operator and that will contain our repeated items. If we run our original input with the duplicated A through find repeated items, we get back an array with that duplication pointed out that A is the only item that was repeated. A proper built-in implementation of the set data structure is truly something that makes Towers script a modern programming language. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36