As a TypeScript developer, you should know how to work with arrays. This page contains all the things you need to know about TypeScript arrays. In this tutorial, I will explain TypeScript arrays in depth, covering everything from the basics to advanced techniques.
Fundamentals of TypeScript Arrays
An array in TypeScript is a collection of values of the same type. We can define an array using square brackets []
. For example, let’s say we want to store a list of US states:
const states: string[] = ['California', 'New York', 'Texas', 'Florida'];
In this example, we’ve declared a constant variable states
of type string[]
, which means it’s an array of strings. We’ve initialized it with four US state names.
Accessing Array Elements
To access individual elements in an array in TypeScript, we use the index notation. Array indices start at 0, so to access the first element, we’d use states[0]
.
console.log(states[0]); // Output: 'California'
console.log(states[2]); // Output: 'Texas'
Modifying Array Elements
We can also modify TypeScript array elements using the index notation. Let’s say we want to change ‘New York’ to ‘Pennsylvania’:
states[1] = 'Pennsylvania';
console.log(states); // Output: ['California', 'Pennsylvania', 'Texas', 'Florida']
Check out
- How to Initialize an Array in TypeScript?
- Append Elements to an Array in TypeScript
- How to Check if a TypeScript Array Contains a Specific Value?
- How to Add Elements to an Array in TypeScript?
- How to Iterate Over Arrays in TypeScript?
- Create and Use an Empty String Array in TypeScript
- Declare and Initialize Empty Arrays in TypeScript
- How to Check if an Array is Empty in TypeScript?
- How to Check if an Array is Not Empty in TypeScript?
- How to Check if an Array is Null or Empty in TypeScript?
- How to Remove an Item from an Array in TypeScript?
- How to Find the Length of an Array in TypeScript?
Common Array Methods in TypeScript
TypeScript provides several built-in methods that make working with arrays more convenient. Let’s explore some of the most commonly used ones.
1. push() and pop()
The push()
method adds one or more elements to the end of an array, while pop()
removes the last element.
const cities: string[] = ['New York', 'Los Angeles', 'Chicago'];
cities.push('Houston');
console.log(cities); // Output: ['New York', 'Los Angeles', 'Chicago', 'Houston']
cities.pop();
console.log(cities); // Output: ['New York', 'Los Angeles', 'Chicago']
2. unshift() and shift()
Similar to push()
and pop()
, unshift()
adds one or more elements to the beginning of an array, while shift()
removes the first element.
const presidents: string[] = ['Barack Obama', 'Donald Trump'];
presidents.unshift('George W. Bush');
console.log(presidents); // Output: ['George W. Bush', 'Barack Obama', 'Donald Trump']
presidents.shift();
console.log(presidents); // Output: ['Barack Obama', 'Donald Trump']
3. slice()
The slice()
method returns a shallow copy of a portion of an array into a new array. It takes two optional parameters: the start index (inclusive) and the end index (exclusive).
const numbers: number[] = [1, 2, 3, 4, 5];
const slicedNumbers = numbers.slice(1, 4);
console.log(slicedNumbers); // Output: [2, 3, 4]
4. splice()
The splice()
method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
const fruits: string[] = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'grape');
console.log(fruits); // Output: ['apple', 'grape', 'orange']
You may also check out:
- How to Reverse an Array in TypeScript?
- How to Calculate the Sum of an Array in TypeScript?
- How to Find an Object in a TypeScript Array?
- How to Work with 2D Arrays in TypeScript?
Advanced TypeScript Array Techniques
Now that we’ve covered the basics, let’s dive into some more advanced concepts and techniques.
Array Destructuring
Array destructuring is a convenient way to extract values from an array and assign them to variables.
const [firstName, lastName] = ['John', 'Doe'];
console.log(firstName); // Output: 'John'
console.log(lastName); // Output: 'Doe'
Spread Operator
The spread operator ...
allows us to expand an array into another array or function arguments.
const easternStates = ['New York', 'New Jersey', 'Massachusetts'];
const westernStates = ['California', 'Oregon', 'Washington'];
const allStates = [...easternStates, ...westernStates];
console.log(allStates); // Output: ['New York', 'New Jersey', 'Massachusetts', 'California', 'Oregon', 'Washington']
Array Mapping
Array mapping is a powerful technique that allows us to transform each element in an array and create a new array with the results.
const kilometers = [1, 2, 3, 4, 5];
const miles = kilometers.map(km => km * 0.621371);
console.log(miles); // Output: [0.621371, 1.242742, 1.864113, 2.485484, 3.106855]
In this example, we’ve converted an array of distances in kilometers to miles using the map()
method.
Array Filtering
Array filtering allows us to create a new array with all the elements that pass a certain condition.
const ages = [18, 25, 32, 40, 16];
const adults = ages.filter(age => age >= 18);
console.log(adults); // Output: [18, 25, 32, 40]
Here, we’ve filtered the ages
array to create a new array adults
containing only the ages greater than or equal to 18.
Check out:
- How to Filter Arrays in TypeScript?
- How to Filter an Array of Objects in TypeScript?
- Get Unique Values from an Array of Objects in TypeScript
- How to Filter an Array of Objects by Multiple Properties in TypeScript?
- How to Merge Arrays of Objects in TypeScript?
Typescript Array: Real-World Example
Let’s apply what we’ve learned to a real-world scenario. Suppose we have an array of objects representing US states and their populations:
interface State {
name: string;
population: number;
}
const stateData: State[] = [
{ name: 'California', population: 39512223 },
{ name: 'Texas', population: 28995881 },
{ name: 'Florida', population: 21477737 },
{ name: 'New York', population: 19453561 },
{ name: 'Illinois', population: 12671821 },
];
We can use array methods to perform various operations on this data. For example, let’s find the total population of all states:
const totalPopulation = stateData.reduce((sum, state) => sum + state.population, 0);
console.log(totalPopulation); // Output: 122110223
We’ve used the reduce()
method to iterate over the array and accumulate the population values into a single sum.
Conclusion
In this tutorial, I have explained TypeScript arrays in depth, covering everything from the basics to advanced techniques. I have also shown how to declare, access, and modify array elements, as well as how to use various array methods like push()
, pop()
, slice()
, and splice()
. Finally, we have gone through more advanced concepts like array destructuring, the spread operator, mapping, and filtering.
I hope you now know how to work with arrays in your TypeScript projects. Do let me know in the comment below.
You may also like to follow the below TypeScript tutorials:
- Arrays of Objects in TypeScript
- How to Sort an Array of Objects by Property Value in TypeScript?
- How to Remove Duplicates from an Array of Objects in TypeScript?
- Find the Maximum Value in an Array of Objects using TypeScript
- Remove Empty Strings from an Array in TypeScript
- How to Get the First Element of an Array in TypeScript?
- How to Get the Last Element of an Array in TypeScript?
- How to Clear an Array in TypeScript While Preserving Its Type?
- How to Convert a Map to an Array in TypeScript?
- How to Find an Object in an Array by Property in TypeScript?
- How to Concatenate Arrays in TypeScript Using concat()?
- How to Check if a Value Exists in an Array in TypeScript?
- How to Flatten an Array of Arrays in TypeScript?
- How to Use Array Reduce() Method in TypeScript?
- How to Use Join() Method to Combine Array of Strings in TypeScript?
- How to Use TypeScript For Loops with Arrays?
- TypeScript Array of Arrays
- How to Convert a Set to an Array in TypeScript?
- How to Convert an Array to a String in TypeScript?
- How to Convert a String to an Array in TypeScript?
- How to Convert an Object to an Array in TypeScript?