Start learning free

LESSON 234 OF 675 · SETS

Sets in TypeScript: Storing Each Value Once

Lesson Read the full explanation

TL ; DR:

A Set holds values without repeats. Adding a value that is already in it changes nothing.


let pets = new Set<string>(["cat", "dog", "cat"]);   // cat goes in once

pets.add("fish");                            // a new value

pets.add("dog");                             // already in it, no change

console.log(pets.size);                      // 3

console.log(pets.has("dog"));                // true


Full lesson:

An array keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Adding a value that is already in it changes nothing.

  • new Set() makes an empty set. Its type is written Set<string> for a set of strings.
  • s.add(x) puts x in the set s.
  • s.has(x) is true when x is in the set.
  • s.size gives how many values the set holds.
  • new Set(arr) builds a set from the array arr. Its repeats go in once.

Checking s.has(x) is fast, even for a big set. An array's includes looks at the values one by one.

Watch the names. A set counts with size, not length. It checks with has, not includes.

A TypeScript set keeps the order you added values in. Still, it has no indexes, so s[0] doesn't work.


Your task

The camp's sign-up array, names, has some names twice. Build a set named kids from it.

Then Zoe signs up, and Ava signs up again. Add both names to kids.

Last, if kids has "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · SETS

    Sets in TypeScript, explained

    What a set is

    An array keeps every value you put in it, repeats included. Sometimes all you need to know is which values there are. A Set is built for that: it holds each value once, and adding a value that is already inside changes nothing.

    let pets = new Set<string>(["cat", "dog", "cat"]);
    
    pets.add("fish");
    pets.add("dog");
    
    console.log(pets.size);
    console.log(pets.has("dog"));
    

    The two console.log calls print 3 and true. The repeated "cat" went in once, "fish" was new, and the second "dog" was ignored.

    The operations

    • new Set<string>() makes an empty set of strings. The part in angle brackets is the type of the values.
    • s.add(x) puts x in the set s.
    • s.has(x) is true when x is in the set and false otherwise.
    • s.size is the number of values in the set. It is a property, so it has no parentheses.
    • new Set(arr) builds a set from an array. Repeats go in once.

    Checking s.has(x) is fast even for a big set, because the set does not look at the values one by one. An array's includes does exactly that.

    Dropping repeats from an array

    The most common use of a set is removing repeats. Build a set from the array, then spread the set back into an array with [...]:

    const names = ["Ava", "Leo", "Ava", "Mia", "Leo"];
    const unique = [...new Set(names)];
    console.log(unique.join(" "), unique.length);
    

    It prints Ava Leo Mia 3. Each name keeps its first position, and the array has 3 names, so a set and an array can be converted back and forth when you need the other one's tools.

    Traps

    • The names differ from arrays. A set counts with size, not length, and it checks with has, not includes. The compiler reports kids.length as an error, but the JavaScript it still writes runs, and kids.length quietly gives undefined. Calling kids.includes("Leo") stops the program with kids.includes is not a function.
    • No indexes. A set has no positions, so s[0] does not give the first value. It gives undefined. Loop with for...of or copy the set into an array with [...s].
    • Order. A TypeScript set remembers the order in which values were added. For new Set([3, 1, 2, 3]), [...s] is 3 1 2, and the second 3 does not move anything.
    • Types are not checked at run time. A Set<number> that is asked about the string "1" answers false, because 1 and "1" are different values.

    The exercise

    A camp's sign-up array names has some names twice. The task is to build a set called kids from it, add Zoe and then Ava, and print Leo is coming if Leo is in the set. The code already prints the number of kids twice.

    1. Build the set: let kids: Set<string> = new Set(names);. Ava and Leo appear twice in the array, so the set holds 3 names: Ava, Leo and Mia.
    2. Add Zoe and Ava with one add call each. Zoe is new, so the size becomes 4. Ava is already there, so she changes nothing.
    3. Test kids.has("Leo") inside an if and print the message.
    let names: string[] = ["Ava", "Leo", "Ava", "Mia", "Leo"];
    
    let kids: Set<string> = new Set(names);
    console.log(kids.size + " kids");
    
    kids.add("Zoe");
    kids.add("Ava");
    console.log(kids.size + " kids");
    
    if (kids.has("Leo")) {
        console.log("Leo is coming");
    }
    

    The output is:

    3 kids
    4 kids
    Leo is coming
    

    Key takeaways

    • A Set holds each value once; adding a repeat does nothing.
    • Use add, has and size, not the array names push, includes and length.
    • new Set(array) is the quickest way to drop repeats from an array.
    • A set has no indexes, so s[0] does not work.
    Keep going with TypeScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free