Featured resource
Tech Upskilling Playbook 2025
Tech Upskilling Playbook

Build future-ready tech teams and hit key business milestones with seven proven plays from industry leaders.

Learn more
  • Labs icon Lab
  • Core Tech
Labs

Guided: Type and Transform Data in Collections

Build confidence in handling complex data structures with this hands-on guided lab on TypeScript collections and transformations. You’ll start by defining strongly typed arrays and objects, then explore both mutating and non-mutating array methods for adding, removing, slicing, and sorting elements. Next, dive into functional patterns with map, filter, and reduce to transform and aggregate data immutably. Learn how to leverage Set for unique value storage and Map for key-value associations, using spread syntax and destructuring to maintain clean, predictable code. By the end of this lab, you’ll be equipped to write robust, type-safe data manipulation code that reduces bugs and improves maintainability.

Labs

Path Info

Level
Clock icon Beginner
Duration
Clock icon 45m
Last updated
Clock icon Aug 31, 2025

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Table of Contents

  1. Challenge

    Introduction

    Welcome to the Guided: Type and Transform Data in Collections Lab. This hands-on Code Lab is designed for JavaScript and TypeScript developers who want to deepen their understanding of typed collections and data transformation techniques. You’ll work with arrays, Set objects, and Map objects using TypeScript’s static typing system and applying functional programming methods to manipulate and transform data in an immutable way.

    Throughout this lab, you’ll practice adding, removing, slicing and sorting elements in arrays, aggregating data using reduce, transforming items with map, filtering subsets with filter, storing unique values using Set, and representing key–value pairs with Map. ### Key Takeaways:

    • Declare and use strongly typed arrays, Set objects, and Map objects in TypeScript
    • Transform and process data using map, filter, and reduce
    • Apply immutability best practices with spread syntax and non-mutating methods
    • Use Set to store unique values and Map to associate keys with values
    • Practice data transformation and aggregation through hands-on exercises ## Prerequisites

    JavaScript and TypeScript Knowledge

    • Familiarity with fundamental JavaScript concepts, including arrays, functions, and objects
    • Basic understanding of TypeScript syntax, such as type annotations, interfaces, and arrow functions

    Tools and Environment Familiarity

    • Comfortable using the Terminal or command line to run scripts
    • Experience with a modern code editor like VS Code, WebStorm, or any TypeScript-compatible IDE
    • Ability to run TypeScript code using ts-node or npm scripts ## Movie Library Dataset

    This lab utilizes a fictional movie library dataset to facilitate your learning. Each step builds on the previous one to transform, group, and analyze a list of movies. You’ll write and test functions that apply various collection techniques and transformations while ensuring type safety. __solution Folder

    • code: The final code for each step is stored in the __solution/code folder. For instance, the final code for Step 2 is available in the __solution/code/Step02 directory.

    • images: This folder contains images depicting the lab's final state for each step. For example, __solution/images/Step02 contains images depicting the final state of Step 2.

  2. Challenge

    Working with Typed `number` Collections

    In this step, you’ll work with a typed number array in TypeScript. You’ll learn how to declare a typed array using square bracket syntax and perform common operations such as adding, inserting, removing, and copying elements while ensuring type safety.

    Explanation
    • const numbers: number[] declares a typed array in TypeScript. This means the array can only contain numbers, ensuring type safety and preventing non-numeric values (such as strings) from being added.
    • push(value) adds one or more elements to the end of the array.
    • unshift(value1, value2) adds one or more elements to the beginning of the array.
    • pop() removes the last element from the array and returns it.
    • shift() removes the first element from the array and returns it.
    • All of these methods mutate the original array, meaning they change its contents directly rather than returning a modified copy.
    • Mutating arrays is fast and memory-efficient, which makes it useful for simple tasks. However, it can lead to bugs, unintended side effects, and make code harder to test and maintain—especially in larger or stateful applications where immutability is preferred.
    Navigate to the **Terminal** and run the following command to test the changes you made:
    npm run dev -- --function=processNumbers
    

    You should see an output in your Terminal similar to the example response below:

    Original numbers array [ 12, 34, 56, 78, 90 ]
    Numbers array after 100 added at the end [ 12, 34, 56, 78, 90, 100 ]
    Numbers array after (101, 102) added at the beginning [
      101, 102, 12,  34,
       56,  78, 90, 100
    ]
    Last number popped 100
    Numbers array after last number popped [
      101, 102, 12, 34,
       56,  78, 90
    ]
    First number removed 101
    Numbers after all operations [ 102, 12, 34, 56, 78, 90 ]
    ``` <details>
    <summary>Explanation</summary>
    
    * `splice(index, deleteCount, ...items)` modifies an array by removing `deleteCount` elements starting at the specified `index`, and optionally inserting new items at that position.
    * To insert items without removing any, set `deleteCount` to `0`. For example, `splice(2, 0, 3)` inserts the number `3` at index `2`.
    * To remove items, set `deleteCount` to a value greater than `0`. For example, `splice(0, 2)` removes two items starting from index `0`.
    * `[...numbers]` uses the spread operator to create a shallow copy of the original `numbers` array. The new array, stored in `newCopiedItems`, contains the same elements but exists at a different memory location. This means changes to `newCopiedItems` do not affect the original `numbers` array.
    * Keep in mind that the `splice()` method mutates the array it is called on, modifying its contents directly.
    
    </details> Navigate to the **Terminal** and run the following command to test the changes you made:
    
    ```tsx
    npm run dev -- --function=addRemoveNumbers
    

    You should see an output in your Terminal similar to the example response below:

    Original numbers array [ 1, 2, 4, 7, 8 ]
    Number array after adding 3 at the second index [ 1, 2, 3, 4, 7, 8 ]
    Number array after adding (5, 6) at the fourth index [
      1, 2, 3, 4,
      5, 6, 7, 8
    ]
    newCopiedItems array after creating new copy [
      1, 2, 3, 4,
      5, 6, 7, 8
    ]
    Removed first two items [ 1, 2 ]
    newCopiedItems array after removing first two items [ 3, 4, 5, 6, 7, 8 ]
    Original numbers array unchanged after removing first two items as new copy was created [
      1, 2, 3, 4,
      5, 6, 7, 8
    ]
    ``` Congratulations! You’ve successfully learned how to declare typed `number` arrays and perform common operations such as inserting, removing, and copying elements using `splice()` and the spread operator. You also explored how these methods mutate arrays and why creating shallow copies is useful for avoiding side effects.
  3. Challenge

    Working with Typed `string` Collections

    In this step, you'll learn how to work with typed string arrays in TypeScript. You'll combine multiple arrays, extract specific elements using slice and sort arrays in both ascending and descending order. These operations are common when managing and transforming collections of string data.

    Explanation
    • string[] defines an array that can contain only string values. This provides type safety by preventing other data types from being added to the array.
    • concat() merges two or more arrays into a new array without changing the original arrays. In this task, it combines petAnimals and wildAnimals into a new array named animals, with pet animals coming first.
    • slice(startIndex?, endIndex?) returns a shallow copy of a portion of the array, starting from startIndex up to but not including endIndex. For example, slice(5, 7) extracts the elements at indices 5 and 6 and assigns them to carnivoreAnimals. This method does not modify the original array.
    • sort() arranges the elements of the array in ascending alphabetical order.
    • reverse() reverses the order of elements in the array. When used after sort(), it results in descending alphabetical order.
    • concat() and slice() are non-mutating methods. They return new arrays without changing the original.
    • sort() and reverse() are mutating methods. They modify the original animals array.
    Navigate to the **Terminal** and run the following command to test the changes you made:
    npm run dev -- --function=processStrings
    

    You should see an output in your Terminal similar to the example response below:

    Pet animals array [ 'cat', 'dog', 'rabbit', 'horse', 'turtle' ]
    Wild animals array [ 'lion', 'tiger', 'leopard' ]
    All animals array [
      'cat',    'dog',
      'rabbit', 'horse',
      'turtle', 'lion',
      'tiger',  'leopard'
    ]
    CarnivoreAnimals array [ 'lion', 'tiger' ]
    All animals array [
      'cat',    'dog',
      'rabbit', 'horse',
      'turtle', 'lion',
      'tiger',  'leopard'
    ]
    Animals array after sorted in ascending order [
      'cat',   'dog',
      'horse', 'leopard',
      'lion',  'rabbit',
      'tiger', 'turtle'
    ]
    Animals array after reverse sort [
      'turtle',  'tiger',
      'rabbit',  'lion',
      'leopard', 'horse',
      'dog',     'cat'
    ]
    ``` Congratulations! In this step, you successfully created and worked with typed `string` arrays using methods such as `concat`, `slice`, `sort`, and `reverse`. You also learned the difference between mutating and non-mutating array operations in TypeScript, and how they affect the original array.
    
  4. Challenge

    Working with Typed `Movie` Collections

    In this step, you will work with an array of typed Movie objects. The Movie type has already been created for this lab. You’ll apply key transformation methods like map(), filter(), and reduce() to enrich the data, extract specific results, and perform numeric aggregation. You'll also utilize TypeScript features such as array annotations, destructuring, and the spread operator to write clean and safe code.

    Explanation
    • Movie[] typing ensures the movies array contains valid Movie objects, providing type safety.
    • map() creates a new array by transforming each item without modifying the original, helping maintain immutability.
    • Typed arrow function (movie: Movie): Movie ensures both input and output confirm to the Movie type.
    • Destructuring simplifies access to title and year within the map() callback.
    • Spread operator (...movie) copies all original properties, allowing safe updates without changing the original object.
    • Template literal builds the displayTitle in "title - year" format for clarity.
    Navigate to the **Terminal** and execute the following command to test the above changes:
    npm run dev -- --function=showDisplayTitle
    

    You should see a response in your Terminal as shown in the example response below:

    Original movies array [
      { slug: 'inception', title: 'Inception', year: 2010, genre: 'Drama', isWatched: true, rating: 6 },
      { slug: 'the-godfather', title: 'The Godfather', year: 1972, genre: 'Crime', isWatched: false, rating: 8 },
      { slug: 'moana', title: 'Moana', year: 2001, genre: 'Animation', isWatched: true, rating: 7 },
      { slug: 'peaky-blinders', title: 'Peaky Blinders', year: 2013, genre: 'Drama', isWatched: true, rating: 9 }
    ]
    
    Movies array with display title [
      { slug: 'inception', title: 'Inception', year: 2010, genre: 'Drama', isWatched: true, rating: 6, displayTitle: 'Inception - 2010' },
      { slug: 'the-godfather', title: 'The Godfather', year: 1972, genre: 'Crime', isWatched: false, rating: 8, displayTitle: 'The Godfather - 1972' },
      { slug: 'moana', title: 'Moana', year: 2001, genre: 'Animation', isWatched: true, rating: 7, displayTitle: 'Moana - 2001' },
      { slug: 'peaky-blinders', title: 'Peaky Blinders', year: 2013, genre: 'Drama', isWatched: true, rating: 9, displayTitle: 'Peaky Blinders - 2013' }
    ]
    ``` <details>
    <summary>Explanation</summary>
    
    - `array.filter(callbackFn)` creates a new array containing only elements that meet a specific condition. In this case, it returns movies where `isWatched` is `true`. The `callbackFn` returns `true` to include an item or `false` to exclude it.
    - Typed arrow function `(movie: Movie): boolean` ensures that the input is a `Movie` type and the function returns a `boolean` type, enforcing type safety.
    - `filter()` does not mutate the original array but returns a new filtered array, preserving the original data. This helps keep the code predictable and free of side effects, which is especially useful in functional or reactive programming.
    
    </details> Navigate to the **Terminal** and execute the following command to test the above changes:
    
    ```tsx
    npm run dev -- --function=showWatchedMovies
    

    You should see a response in your Terminal as shown in the example response below:

    Original movies array [
      { slug: 'inception', title: 'Inception', year: 2010, genre: 'Drama', isWatched: true, rating: 6 },
      { slug: 'the-godfather', title: 'The Godfather', year: 1972, genre: 'Crime', isWatched: false, rating: 8 },
      { slug: 'moana', title: 'Moana', year: 2001, genre: 'Animation', isWatched: true, rating: 7 },
      { slug: 'peaky-blinders', title: 'Peaky Blinders', year: 2013, genre: 'Drama', isWatched: true, rating: 9 }
    ]
    
    Watched movies array [
      { slug: 'inception', title: 'Inception', year: 2010, genre: 'Drama', isWatched: true, rating: 6 },
      { slug: 'moana', title: 'Moana', year: 2001, genre: 'Animation', isWatched: true, rating: 7 },
      { slug: 'peaky-blinders', title: 'Peaky Blinders', year: 2013, genre: 'Drama', isWatched: true, rating: 9 }
    ]
    ``` <details>
    <summary>Explanation</summary>
    
    - `array.reduce((accumulator, currentItem) => result, initialValue)` is used to iterate over an array and accumulate a single result. In this case, it calculates the total of all movie ratings. The initial value of `acc` is `0`, and `movie.rating` is added to it during each iteration.
    - `reduce()` does not mutate the original array. It returns a single aggregated value while preserving the original data, keeping the logic predictable and safe for functional programming.
    
    </details> Navigate to the **Terminal** and execute the following command to test the above changes:
    
    ```tsx
    npm run dev -- --function=showTotalRatings
    

    You should see a response in your Terminal as shown in the example response below:

    Original movies array [
      { slug: 'inception', title: 'Inception', year: 2010, genre: 'Drama', isWatched: true, rating: 6 },
      { slug: 'the-godfather', title: 'The Godfather', year: 1972, genre: 'Crime', isWatched: false, rating: 8 },
      { slug: 'moana', title: 'Moana', year: 2001, genre: 'Animation', isWatched: true, rating: 7 },
      { slug: 'peaky-blinders', title: 'Peaky Blinders', year: 2013, genre: 'Drama', isWatched: true, rating: 9 }
    ]
    Total rating 30
    Average rating 7.50
    ``` Congratulations! You've successfully learned how to transform, filter, and reduce a typed collection in TypeScript using powerful array methods like `map()`, `filter()`, and `reduce()`. Along the way, you applied best practices like type annotations, destructuring, and immutability, which are essential skills for working with structured data in real-world TypeScript applications.
  5. Challenge

    Working with `Set` Collections

    In this step, you’ll learn how to work with the Set collection in TypeScript. A Set is a special type of collection that only stores unique values. You’ll extract genres from movie data, eliminate duplicates, and perform operations like checking for an item, adding new values, and removing values from the Set.

    Explanation
    • map() is used to create a new array containing only the genre values from each movie object.
    • Set<string> automatically removes any duplicate values, ensuring unique genres are stored in the genres variable.
    • This task highlights how Set helps simplify the deduplication of values in a collection.
    Navigate to the **Terminal** and execute the following command to test the above changes:
    npm run dev -- --function=showGenres
    

    You should see a response in your Terminal as shown in the example response below:

    All genres in the movie data [ 'Drama', 'Crime', 'Animation', 'Drama' ]
    Unique genres using Set collection Set(3) { 'Drama', 'Crime', 'Animation' }
    ``` <details>
    <summary>Explanation</summary>
    
    - `Set.has(value)` checks whether a specific item exists in the `Set` and returns a boolean result.
    - `Set.add(value)` inserts a new unique item into the `Set`. If the item already exists, it will not be added again.
    - `Set.delete(value)` removes an item from the `Set` if it exists.
    - A `for...of` loop is used to iterate over the items in a `Set`, as a `Set` is iterable.
    - `Set` operations are fast and ideal for managing collections where uniqueness is important.
    - These methods mutate the original `Set`, which is acceptable in scenarios where stateful updates are expected.
    
    </details> Navigate to the **Terminal** and execute the following command to test the above changes:
    
    ```tsx
    npm run dev -- --function=processGenres
    

    You should see a response in your Terminal as shown in the example response below:

    Genre Set has animation
    Unique genres after added data Set(5) { 'Drama', 'Crime', 'Animation', 'Comedy', 'Love Story' }
    Unique genres after Crime is deleted:
    Drama
    Animation
    Comedy
    Love Story
    ``` Congratulations! In this step, you learned how to use `Set` in TypeScript to handle unique collections. You successfully extracted data, eliminated duplicates using `Set` objects, and performed operations like checking, adding, deleting, and iterating over items. `Set` objects are powerful tools when working with collections that require uniqueness and fast lookups.
  6. Challenge

    Working with `Map` Collections

    In this step, you will learn how to use the Map collection in TypeScript to store and manage key-value pairs. Map objects are useful for associating values with specific keys. For example, you can use them to aggregate movie ratings by genre. You’ll practice using Map methods such as get, set, has, and delete to manage the structured data.

    Explanation
    • Map<string, number> allows you to associate each genre (string) with its total rating (number).
    • The get() method retrieves the current total rating for a genre (movie.genre). It returns undefined if the key does not exist.
    • The set() method updates the map by storing the current movie’s rating added to the existing total for that genre.
    • Map objects provide an efficient way to store and retrieve values associated with specific keys.
    Navigate to the **Terminal** and execute the following command to test the above changes:
    npm run dev -- --function=showGenresWithRatings
    

    You should see a response in your Terminal as shown in the example response below:

    Total rating of each genre using Map Map(3) { 'Drama' => 15, 'Crime' => 8, 'Animation' => 7 }
    ``` <details>
    <summary>Explanation</summary>
    
    - `has()` checks if a genre key exists in the `Map` and returns a boolean value.
    - `get()` retrieves the value for a given key — in this case, the total rating for `Crime`.
    - `delete()` removes the key–value pair from the `Map` if it exists.
    - These operations demonstrate how to check for, access, modify, and delete an item in a `Map` collection.
    
    </details>
     Navigate to the **Terminal** and execute the following command to test the above changes:
    
    ```tsx
    npm run dev -- --function=processGenresWithRatings
    

    You should see a response in your Terminal as shown in the example response below:

    Genres all Map(3) { 'Drama' => 15, 'Crime' => 8, 'Animation' => 7 }
    Crime Genres Total Rating 8
    Genres after Crime is deleted Map(2) { 'Drama' => 15, 'Animation' => 7 }
    ``` You’ve successfully learned how to use the `Map` collection in TypeScript to group, access, and update data. By applying methods like `get`, `set`, `has`, and `delete`, you can efficiently manage structured data, such as aggregated movie ratings by genre.
    
    Congratulations! You’ve successfully completed the lab.

Asmin Bhandari is a full stack developer with years of experience in designing, developing and testing many applications and web based systems.

What's a lab?

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Provided environment for hands-on practice

We will provide the credentials and environment necessary for you to practice right within your browser.

Guided walkthrough

Follow along with the author’s guided walkthrough and build something new in your provided environment!

Did you know?

On average, you retain 75% more of your learning if you get time for practice.