Typescript Arrays

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

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:

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:

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: