Introduction and Overview

Are you ready for a TypeScript journey? In this lesson, we'll delve into Simple Data Structures and Advanced Array Operations. You'll master the creation, manipulation, and access of elements in both single and multi-dimensional arrays. Imagine managing a task list for a software development project where each array element could be a feature with its own array of sub-features – exciting, isn't it? Let's dive in!

Creation of Multi-Dimensional Arrays

Multi-dimensional arrays behave like clusters with each item being an array itself, akin to clusters of data units.

Creating a multi-dimensional array is straightforward: simply place an array inside another array, as shown here:

let multiArray: any[][] = [[1, 2, 3], ['a', 'b', 'c'], [true, false]];
console.log(multiArray); // Output: [ [ 1, 2, 3 ], [ 'a', 'b', 'c' ], [ true, false ] ]

In this case, we have a multi-dimensional array of three elements, each of which is also an array.

Array Indexing

Accessing elements in a multi-dimensional array relies on indexes. The first index points to the outer array, while the second one points to the inner array:

let multiArray: any[][] = [[1, 2, 3], ['a', 'b', 'c'], [true, false]];

// Accessing the first array
console.log(multiArray[0]); // Output: [ 1, 2, 3 ]
console.log(multiArray[0][0]); // Output: 1
console.log(multiArray[0][1]); // Output: 2

Working with multi-dimensional arrays and indexing will enhance your understanding of handling complex data!

Modifying Array Elements

Just as we modify elements in a one-dimensional array, you can modify elements in a multi-dimensional array using their indices. The first index points to the outer array (or the sub-array), while the second index points to the item inside (or the element in the sub-array):

let multiArray: any[][] = [[1, 2, 3], ['a', 'b', 'c'], [true, false]];

// Modifying an element in the first array
multiArray[0][0] = 100;
console.log(multiArray); // Output: [ [ 100, 2, 3 ], [ 'a', 'b', 'c' ], [ true, false ] ]

// Modifying an element in the second array
multiArray[1][2] = 'z';
console.log(multiArray); // Output: [ [ 100, 2, 3 ], [ 'a', 'b', 'z' ], [ true, false ] ]

It is also possible to add or remove elements to and from multi-dimensional arrays, thereby changing their structure:

multiArray[0].push(4);
console.log(multiArray); // Output: [ [ 100, 2, 3, 4 ], [ 'a', 'b', 'z' ], [ true, false ] ]

multiArray[1].pop();
console.log(multiArray); // Output: [ [ 100, 2, 3, 4 ], [ 'a', 'b' ], [ true, false ] ]
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