Introduction

Welcome to our exploration of Compound Data Structures in JavaScript. Having navigated through Maps, Sets, and Arrays, we'll delve into nested Maps and 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.

Nested Map:

// Map within a Map
const nestedMap = new Map([
    ['fruit', new Map([
        ['apple', 'red'],  // key-value pair within the 'fruit' map
        ['banana', 'yellow']  // another key-value pair within the 'fruit' map
    ])],
    ['vegetable', new Map([
        ['carrot', 'orange'],
        ['spinach', 'green']
    ])]
]);

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

Nested Array:

// Arrays within an array
const nestedArray = [
    [1, 2, 3],  // inner array within the outer array
    [4, 5, 6],  // another inner array within the outer array
    [7, 8, 9]   // third inner array within the outer array
];

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

Nested Maps and Arrays:

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

// Logs the Map of arrays
console.log(arrayMap);
Accessing Values in Nested Structures
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