Arrays and Tuples in TypeScript
Understand how to work with arrays and tuples in TypeScript. We'll cover declaring, initializing, and manipulating these data structures.
TypeScript Array Manipulation for Beginners
Understanding Arrays in TypeScript
An array is a data structure that holds an ordered collection of items. These items can be of the same type (e.g., all numbers) or of mixed types (though it's generally good practice to stick to a single type). In TypeScript, you can explicitly define the type of elements an array can hold.
// Example: An array of numbers
let numbers: number[] = [1, 2, 3, 4, 5];
// Example: An array of strings
let names: string[] = ["Alice", "Bob", "Charlie"];
// Example: An array of any type (less common, but possible)
let mixed: any[] = [1, "Hello", true];
Declaring array types is crucial for TypeScript's type checking and helps prevent errors in your code.
Adding Elements to an Array
There are several ways to add elements to an array:
Using push()
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
let fruits: string[] = ["apple", "banana"];
fruits.push("orange"); // Adds "orange" to the end
console.log(fruits); // Output: ["apple", "banana", "orange"]
fruits.push("grape", "kiwi"); // Adds multiple elements
console.log(fruits); // Output: ["apple", "banana", "orange", "grape", "kiwi"]
Using unshift()
The unshift()
method adds one or more elements to the beginning of an array and returns the new length of the array.
let fruits: string[] = ["apple", "banana"];
fruits.unshift("orange"); // Adds "orange" to the beginning
console.log(fruits); // Output: ["orange", "apple", "banana"]
fruits.unshift("grape", "kiwi"); // Adds multiple elements
console.log(fruits); // Output: ["grape", "kiwi", "orange", "apple", "banana"]
Using the Spread Operator (...
)
The spread operator allows you to insert elements into an array at any position, creating a new array without modifying the original. This is a powerful and often preferred method for immutability.
let fruits: string[] = ["apple", "banana"];
let moreFruits: string[] = ["orange", "grape"];
// Add moreFruits to the end of fruits:
let allFruits: string[] = [...fruits, ...moreFruits];
console.log(allFruits); // Output: ["apple", "banana", "orange", "grape"]
// Add moreFruits to the beginning of fruits:
let allFruits2: string[] = [...moreFruits, ...fruits];
console.log(allFruits2); // Output: ["orange", "grape", "apple", "banana"]
// Insert elements in the middle (more complex):
let insertMiddle: string[] = [...fruits.slice(0, 1), ...moreFruits, ...fruits.slice(1)];
console.log(insertMiddle); // Output: ["apple", "orange", "grape", "banana"]
Removing Elements from an Array
There are several ways to remove elements from an array:
Using pop()
The pop()
method removes the last element from an array and returns that element. It modifies the original array.
let fruits: string[] = ["apple", "banana", "orange"];
let lastFruit: string | undefined = fruits.pop(); // Removes "orange"
console.log(fruits); // Output: ["apple", "banana"]
console.log(lastFruit); // Output: "orange" (or undefined if the array was empty)
Using shift()
The shift()
method removes the first element from an array and returns that element. It modifies the original array.
let fruits: string[] = ["apple", "banana", "orange"];
let firstFruit: string | undefined = fruits.shift(); // Removes "apple"
console.log(fruits); // Output: ["banana", "orange"]
console.log(firstFruit); // Output: "apple" (or undefined if the array was empty)
Using splice()
The splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It is very versatile.
let fruits: string[] = ["apple", "banana", "orange", "grape"];
// Remove 1 element starting at index 1 (banana):
fruits.splice(1, 1);
console.log(fruits); // Output: ["apple", "orange", "grape"]
// Remove 2 elements starting at index 0 (apple, orange) and add "kiwi":
fruits.splice(0, 2, "kiwi");
console.log(fruits); // Output: ["kiwi", "grape"]
// Remove 0 elements at index 1 and insert "mango" and "melon":
fruits.splice(1, 0, "mango", "melon");
console.log(fruits); // Output: ["kiwi", "mango", "melon", "grape"]
Using slice()
(for creating a new array without the removed elements)
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from start
to end
(end
not included) where start
and end
represent the index of items in that array. The original array will not be modified.
let fruits: string[] = ["apple", "banana", "orange", "grape"];
// Create a new array with elements from index 1 to the end:
let newFruits1: string[] = fruits.slice(1);
console.log(newFruits1); // Output: ["banana", "orange", "grape"]
console.log(fruits); // Output: ["apple", "banana", "orange", "grape"] (original array unchanged)
// Create a new array with elements from index 1 to (but not including) index 3:
let newFruits2: string[] = fruits.slice(1, 3);
console.log(newFruits2); // Output: ["banana", "orange"]
console.log(fruits); // Output: ["apple", "banana", "orange", "grape"] (original array unchanged)
Filtering an Array
The filter()
method creates a new array with all elements that pass the test implemented by the provided function. This is useful for creating new arrays based on conditions.
let numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Create a new array with only even numbers:
let evenNumbers: number[] = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (original array unchanged)
Accessing Elements by Index
You can access elements in an array using their index. Array indices start at 0.
let fruits: string[] = ["apple", "banana", "orange"];
console.log(fruits[0]); // Output: "apple"
console.log(fruits[1]); // Output: "banana"
console.log(fruits[2]); // Output: "orange"
//Trying to access an out-of-bounds index will return `undefined`
console.log(fruits[3]); // Output: undefined
Iterating Through Arrays
You can iterate through an array to access each element. Here are a few common methods:
Using a for
loop
let fruits: string[] = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(`Fruit at index ${i}: ${fruits[i]}`);
}
// Output:
// Fruit at index 0: apple
// Fruit at index 1: banana
// Fruit at index 2: orange
Using forEach()
The forEach()
method executes a provided function once for each array element.
let fruits: string[] = ["apple", "banana", "orange"];
fruits.forEach(function(fruit, index) {
console.log(`Fruit at index ${index}: ${fruit}`);
});
// Output:
// Fruit at index 0: apple
// Fruit at index 1: banana
// Fruit at index 2: orange
You can also use arrow function syntax for a more concise version:
let fruits: string[] = ["apple", "banana", "orange"];
fruits.forEach((fruit, index) => {
console.log(`Fruit at index ${index}: ${fruit}`);
});
// Output:
// Fruit at index 0: apple
// Fruit at index 1: banana
// Fruit at index 2: orange
Using a for...of
loop (Modern JavaScript)
The for...of
statement creates a loop iterating over iterable objects, including arrays.
let fruits: string[] = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(`Fruit: ${fruit}`);
}
// Output:
// Fruit: apple
// Fruit: banana
// Fruit: orange
Array Destructuring
Array destructuring is a concise way to extract values from an array and assign them to variables.
let fruits: string[] = ["apple", "banana", "orange"];
// Assign the first three elements to variables:
let [firstFruit, secondFruit, thirdFruit] = fruits;
console.log(firstFruit); // Output: "apple"
console.log(secondFruit); // Output: "banana"
console.log(thirdFruit); // Output: "orange"
// Skip elements:
let [, , onlyThirdFruit] = fruits; //skips first and second element
console.log(onlyThirdFruit); //Output: "orange"
// Use the rest operator to capture remaining elements:
let [head, ...tail] = fruits;
console.log(head); // Output: "apple"
console.log(tail); // Output: ["banana", "orange"]
Other Useful Array Methods
TypeScript/JavaScript provides a rich set of built-in array methods. Here are a few more that are commonly used:
map()
: Creates a new array with the results of calling a provided function on every element in the calling array.reduce()
: Executes a reducer function (that you provide) on each element of the array, resulting in a single output value.find()
: Returns the value of the *first* element in the provided array that satisfies the provided testing function. Otherwise `undefined` is returned.findIndex()
: Returns the *index* of the *first* element in the array that satisfies the provided testing function. Otherwise, it returns -1.includes()
: Determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate.sort()
: Sorts the elements of an array *in place* and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. Be careful with numeric sorts!
Refer to the Mozilla Developer Network (MDN) documentation for a comprehensive list and detailed explanations of all available array methods: MDN Array Documentation