Introduction

Welcome to our exploration of Compound Data Structures in TypeScript. Having navigated through Maps, Sets, and Arrays, we'll delve into Nested Maps and Nested Arrays. These structures enable us to handle complex and hierarchical data, which is typical in real-world scenarios. Nested data structures are commonly used to represent data models like organizational charts, product categories, and multi-dimensional datasets. This lesson will guide you through a recap of the basics, as well as the creation and modification of nested Maps and Arrays.

Recap: Maps, Arrays, and Understanding Nested Structures

As a quick recap, Arrays are mutable, ordered collections, while Maps are collections of key-value pairs with maintained insertion order. These structures can be nested. Here's a simple example of a school directory:

// Map with grades as keys and arrays of students as values
const schoolDirectory = new Map([
    ['Grade1', ['Amy', 'Bobby', 'Charlie']],
    ['Grade2', ['David', 'Eve', 'Frank']],
    ['Grade3', ['George', 'Hannah', 'Ivy']]
]);

// Logs the Grade1 array in the Map
console.log(schoolDirectory.get('Grade1')); // Output: ['Amy', 'Bobby', 'Charlie']
Creating Nested Maps and Arrays

Just like their non-nested versions, creating nested structures is straightforward, with added type safety in TypeScript.

Nested Map:

// Map within a Map
const nestedMap = new Map([
    ['fruit', new Map([
        ['apple', 'red'],  
        ['banana', 'yellow']
    ])],
    ['vegetable', new Map([
        ['carrot', 'orange'],
        ['spinach', 'green']
    ])]
]);

// Logs the nested map
console.log(nestedMap);

Nested Array:

// Arrays within an array
const nestedArray: number[][] = [
    [1, 2, 3],  
    [4, 5, 6],  
    [7, 8, 9]
];

// Logs the nested array
console.log(nestedArray);

Nested Maps and Arrays:

// Arrays within a Map
const arrayMap = new Map([
    ['numbers', [1, 2, 3]],  
    ['letters', ['a', 'b', 'c']]
]);

// Logs the Map of arrays
console.log(arrayMap);
Accessing Values in Nested Structures

The retrieval of values from nested Maps or arrays is facilitated by TypeScript's type-checking, which ensures that operations are performed on valid structures.

From Nested Map:

// Accessing apple's color from the nested Map
const nestedMap = new Map([
    ['fruit', new Map([
        ['apple', 'red'],  
        ['banana', 'yellow']
    ])],
    ['vegetable', new Map([
        ['carrot', 'orange'],
        ['spinach', 'green']
    ])]
]);

// Accessing apple's color from the nested Map
const appleColor = nestedMap.get('fruit')?.get('apple');
console.log(appleColor); // Output: 'red'

In this code example, the optional chaining operator (?.) is used in nestedMap.get('fruit')?.get('apple') to avoid errors:

  • nestedMap.get('fruit') attempts to access the nested Map associated with the 'fruit' key.
  • The ?. operator ensures that if 'fruit' does not exist (i.e., returns undefined), it does not attempt to call .get('apple'), which would cause an error.
  • Instead, the expression safely evaluates to undefined if 'fruit' is missing, preventing a runtime error.
  • If 'fruit' is present, then .get('apple') executes normally, retrieving the color 'red'.

From Nested Array:

// Accessing the 3rd value from the 2nd array in the nested array
const nestedArray: number[][] = [
    [1, 2, 3],  
    [4, 5, 6],  
    [7, 8, 9]
];


const thirdValue = nestedArray[1]?.[2];
console.log(thirdValue); // Output: 6

From Both:

// Accessing the second letter in the 'letters' array in arrayMap
const arrayMap = new Map([
    ['numbers', [1, 2, 3]],  
    ['letters', ['a', 'b', 'c']]
]);

const secondLetter = arrayMap.get('letters')?.[1];
console.log(secondLetter); // Output: 'b'
Error Handling in Nested Data Structures

While retrieving data from nested Maps or arrays, it's important to handle potential errors gracefully. This can be done using conditional checks or try-catch blocks.

Error Handling with Nested Maps and Arrays:

For nested Maps and arrays, check the existence of keys and valid indices.

// Safely accessing the color of apple
if (nestedMap.has('fruit') && nestedMap.get('fruit').has('apple')) {
    console.log(nestedMap.get('fruit').get('apple')); // Output: 'red'
} else {
    console.error('The key "apple" or "fruit" does not exist.');
}

// Safely accessing the 3rd value from the 2nd array
if (nestedArray[1] && nestedArray[1][2] !== undefined) {
    console.log(nestedArray[1][2]); // Output: 6
} else {
    console.error('The index is out of bounds.');
}

// Safely accessing the second letter in the 'letters' array
if (arrayMap.has('letters') && arrayMap.get('letters')[1] !== undefined) {
    console.log(arrayMap.get('letters')[1]); // Output: 'b'
} else {
    console.error('The key "letters" or index is out of bounds.');
}

Using try-catch for Error Handling:

Alternatively, you can use try-catch blocks to handle errors.

try {
    console.log(nestedMap.get('fruit').get('apple')); // Output: 'red'
} catch (error) {
    console.error('Error accessing nested key:', error.message);
}

try {
    console.log(nestedArray[1][2]); // Output: 6
} catch (error) {
    console.error('Error accessing nested array:', error.message);
}

try {
    console.log(arrayMap.get('letters')[1]); // Output: 'b'
} catch (error) {
    console.error('Error accessing map with array:', error.message);
}

By implementing these error handling techniques, you can ensure your code is more robust and resilient against common issues with nested data structures.

Common Operations on These Structures

Modification of nested arrays and Maps is similar to non-nested versions, and TypeScript ensures that these operations conform to defined types.

// Modifying spinach's color to red
nestedMap.get('vegetable')?.set('spinach', 'red');

// Adding 10 to the first array in nested array
nestedArray[0]?.push(10);

// Adding cherry to the 'fruit' Map in nestedMap
nestedMap.get('fruit')?.set('cherry', 'red');

// Deleting the 2nd value from the 3rd array in nested array
nestedArray[2]?.splice(1, 1); // Remove 1 element at index 1

// Deleting apple from the 'fruit' Map in nestedMap
nestedMap.get('fruit')?.delete('apple');
Lesson Summary

Bravo! You've made a journey through nested arrays and Maps, terms that are becoming increasingly common in the data-intensive programming world. We've learned how to create, access, and modify values in these complex structures using TypeScript to ensure type safety and prevent errors. Up next, we have hands-on practice sessions to solidify your understanding of these concepts. Hold on to your hats!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal