close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than whatโ€™s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

Array TS Basics for Beginners

Array TS Basics for Beginners
Author
Nimrod Kramer
Related tags on daily.dev
toc
Table of contents
arrow-down

๐ŸŽฏ

Learn the basics of arrays in TypeScript, including type safety, manipulation methods, accessing elements, iterating over arrays, and working with complex data. Simplifying arrays in TypeScript for beginners.

TypeScript enhances JavaScript by adding type safety, making coding more secure and efficient. Arrays in TypeScript, a fundamental aspect, organize data for easy manipulation. Here's what you need to know:

  • Arrays store multiple items under one name, in a specific order.
  • Type safety ensures each array holds items of a specified type, reducing errors.
  • Manipulation methods like push, pop, and map allow easy data handling.
  • Typed arrays declare the type of elements they contain, ensuring consistency.
  • Accessing and modifying elements is straightforward, using indexes or array methods.
  • Iterating over arrays can be done with loops or methods like forEach and map.
  • Advanced methods provide powerful tools for working with array data.
  • Complex data like objects or multi-dimensional arrays can be managed within arrays.

This guide simplifies arrays in TypeScript, making it accessible for beginners to understand and apply these concepts in real-world scenarios.

What is an Array?

Array

An array is like a box where you can store things of the same kind in a row. Imagine you have a box for your socks, one for your pens, and so on.

Here are a few things to know about arrays:

  • Arrays let you keep lots of items under one name. This is better than having to remember a bunch of different names for each item.
  • The items in an array are in a specific order, and each one has a special number called an index.
  • Arrays come with handy tools (like push, pop, shift, unshift) that make it easy to add or take away items.
  • Arrays can grow or shrink in size when you add or remove items.

TypeScript and Arrays

TypeScript adds some rules to arrays that make sure everything in the box matches. Here's what that means:

  • When you say what's going to be in your array in TypeScript (like numbers or words), you have to stick to it.
  • TypeScript checks your work to make sure you're only putting the right kind of things in your array.
  • This helps stop mistakes where you might accidentally put a word in a box meant for numbers.

Here's how you might set up arrays in TypeScript:

let numbers: number[] = [1, 2, 3]; 

let fruits: Array<string> = ['Apple', 'Banana']; 

By making sure everything in the array is the type it's supposed to be, TypeScript helps you catch mistakes early. This way, you can make your website or app work better without running into problems later on.

Declaring Arrays in TypeScript

When you want to make a list in TypeScript, there are a few ways to do it. Using the right method from the start helps you avoid problems later.

Basic Declaration

The easiest way to make a list is with square brackets []. This is just like in JavaScript:

let fruits = ['Apple', 'Banana'];

Or, you can use the Array<T> way to say what type of things your list will hold:

let fruits: Array<string> = ['Apple', 'Banana'];

Using Array<T> lets TypeScript check your list more carefully to make sure everything in it is the right type.

Typed Arrays

To make sure your list really sticks to one type of thing (like only strings or only numbers), you can be clear about it from the start:

let fruits: string[] = ['Apple', 'Banana'];
let numbers: number[] = [1, 2, 3];

This way, TypeScript knows exactly what should be in your list. If you try to mix things up, like adding a number to a list of strings, TypeScript will let you know that's not allowed:

let fruits: string[] = ['Apple', 'Banana'];
fruits.push(5); // Error: number is not assignable to string[]

So, making your list with a specific type helps keep things straight and prevents mistakes.

Accessing and Modifying Array Elements

Accessing Elements

To get to an item in a TypeScript array, we use square brackets and the place number (index) of the item we're after.

For example:

let fruits: string[] = ['Apple', 'Banana', 'Orange'];

let firstFruit = fruits[0]; // Gets 'Apple', the first item

Remember, in arrays, we start counting from 0. So, the first item is at 0, the second at 1, and so on.

If we want to change an item, we just use its index:

fruits[1] = 'Strawberry'; // Changes the second item to 'Strawberry'

Some handy methods to find or check items:

  • indexOf('value') - Finds the place number of a specific item
  • includes('value') - Checks if the array has a certain item
  • find(x => x > 2) - Looks for the first item that meets a condition

Modifying Elements

Here are some main ways to change arrays in TypeScript:

Push & Pop

To add an item to the end:

fruits.push('Grape'); // Adds 'Grape' to the end

To take off the last item:

let last = fruits.pop(); // Takes off the last item

Unshift & Shift

To add to the start:

fruits.unshift('Strawberry'); // Adds 'Strawberry' to the start

To remove the first item:

let first = fruits.shift(); // Takes off the first item

Splice

To insert or replace items anywhere:

fruits.splice(1, 0, 'Lemon', 'Kiwi'); // Adds 'Lemon' and 'Kiwi' at index 1

To take out items:

fruits.splice(0, 2); // Removes the first 2 items

Splice is a flexible way to add or remove items exactly where we want.

Iterating Over Arrays

Going through arrays step by step lets you work with each item one at a time. This is handy for tasks like showing items on a website, looking for specific items, changing data in the array, or adding up values.

Here are some common ways to do this in TypeScript:

For Loops

A simple for loop lets you run some code over and over, perfect for checking each item in an array:

let fruits: string[] = ['Apple', 'Banana', 'Orange'];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]); 
}

This goes through the array and shows each fruit.

forEach

The forEach method runs a function for each item in the array:

fruits.forEach(fruit => {
  console.log(fruit);
});

You just give it a function that says what to do with each item.

for...of

The for...of loop goes directly through the array items:

for (const fruit of fruits) {
  console.log(fruit); 
}

It automatically gets each item for you.

The method you choose depends on your needs, but forEach and for...of make it easier since you don't have to keep track of the item numbers.

Breaking Early

If you want to stop going through the array before reaching the end, you can use break:

fruits.forEach(fruit => {
  if (fruit === 'Banana') {
    break;
  }
  console.log(fruit); 
}); 

This stops the loop when it finds 'Banana'.

Continuing

If you want to skip over an item and keep going, you can use continue:

for (const fruit of fruits) {
  if (fruit === 'Banana') {
    continue;
  }
  console.log(fruit);
}

This skips 'Banana' but continues with the rest.

So, TypeScript gives you several ways to go through arrays, from simple to more specific methods. Pick the one that best fits what you're trying to do.

Advanced Array Methods

TypeScript arrays have a lot of built-in methods, or shortcuts, that make it easier to handle common tasks. Think of these methods as tools that help you manage lists without having to write a lot of repetitive code.

Let's dive into some of the most helpful array methods and see what you can do with them.

Comprehensive List and Usage

Here's a list of key methods you can use with arrays in TypeScript and how to use them:

Iteration Methods

These methods are all about going through the items in your arrays one by one:

  • forEach - Runs a function on each item:
let numbers = [1, 2, 3];

numbers.forEach(n => {
  console.log(n); 
});
  • map - Makes a new array by applying a function to each item:
let squared = numbers.map(n => n * n); 
  • filter - Makes a new array with items that meet a certain condition:
let evens = numbers.filter(n => n % 2 === 0);
  • reduce - Combines all items into one value using a function:
let sum = numbers.reduce((prev, cur) => prev + cur); 
  • every - Checks if all items meet a condition:
let allPositive = numbers.every(n => n > 0);
  • some - Checks if any item meets a condition:
let hasNegative = numbers.some(n => n < 0);

Accessor Methods

These help you find or access items in your array:

  • indexOf - Finds the first place an item appears:
let firstIndexOfFive = [1, 5, 5].indexOf(5); 
  • lastIndexOf - Finds the last place an item appears
  • find - Finds the first item that matches a condition:
let found = [1, 5 ,10].find(n => n > 5);
  • findIndex - Finds the place number of the first item that matches
  • includes - Checks if an item is in the array:
let hasFive = [1, 5, 10].includes(5); 

Mutator Methods

These methods change your array directly:

  • push / pop - Adds or removes items from the end
  • unshift / shift - Adds or removes items from the start
  • splice - Adds or removes items from anywhere in the array:
let removed = arr.splice(2, 1); // Remove 1 item at index 2
  • fill - Changes all items to a single value
  • copyWithin - Copies a part of the array to another place in the same array

Order Methods

These methods sort or reorder your array:

  • reverse - Turns your array backwards
  • sort - Arranges your items in order

These are just a few of the methods available, but they're some of the most important ones for everyday tasks. For a full list, check out the Array reference. Knowing these methods can save you time and make your code cleaner and more efficient. Try practicing with these to get comfortable with how they work.

Arrays of Objects and Multi-Dimensional Arrays

Handling Complex Data

Arrays in TypeScript aren't just for simple stuff like numbers or words. They can handle more complex things, too. You can put together objects with specific details or even make arrays that hold other arrays. This is great for organizing more complicated info.

Here's what you can do with arrays:

  • Custom objects - If you have a specific type of data you're working with, like info about fruits, you can set up a structure for that data and then make an array filled with it:
interface Fruit {
  name: string;
  color: string;
}

let fruits: Fruit[] = [
  {name: 'Apple', color: 'red'},
  {name: 'Banana', color: 'yellow'}, 
];
  • Arrays within arrays - You can have arrays inside other arrays. This is useful for things like tables of data:
let table: string[][] = [
  ['Name', 'Color'],
  ['Apple', 'Red'],
  ['Banana', 'Yellow'],
];
  • Mixed data types - Sometimes, you might need an array that can hold different types of things, like numbers and words together:
let stuff: (number|string)[] = [1, 'two', 3]; 

Working with Complex Arrays

  • To get to something in a nested array, you use more than one index, like pointing to a spot on a map:
let fruitName = table[1][0]; // 'Banana'
  • You can use methods like forEach and map on these complex arrays, too.
  • It's possible to filter through these arrays based on specific details inside them.
  • And you can use methods to combine data from objects in an array to get a summary of the info.

Handling more detailed data with arrays gives you a lot of flexibility. The cool part is, the usual ways to work with arrays still apply, even when things get complex.

sbb-itb-bfaad5b

Practical Examples and Use Cases

Real-World Applications

Let's look at some common ways arrays are used in TypeScript projects and some smart ways to work with them:

Shopping Cart

Imagine you're building a shopping cart for a website. You can use arrays to keep track of what's in the cart. First, we define what info we want for each item in the cart:

interface CartItem {
  name: string;
  price: number;
  quantity: number;
}

let cart: CartItem[] = [];

Next, we can write functions to add, change, and remove items:

function addItem(name: string, price: number, quantity: number) {
  cart.push({
    name, 
    price,
    quantity
  });
}

function updateItem(index: number, quantity: number) {
  cart[index].quantity = quantity; 
}

function removeItem(index: number) {
  cart.splice(index, 1);
}

Smart moves:

  • Use clear structures for your data
  • Write functions to work with the cart
  • Change items using their position

To-Do App

Arrays are perfect for keeping a list of tasks in a simple to-do app:

interface ToDo {
  text: string;
  completed: boolean; 
}

let todos: ToDo[] = [];

We can make functions to add tasks, mark them as done, and show only the ones still pending:

function addToDo(text: string) {
  todos.push({
    text,
    completed: false
  });
}

function completeToDo(index: number) {
  todos[index].completed = true;
}

function getPending() {
  return todos.filter(todo => !todo.completed);
}

Smart moves:

  • Use a simple yes/no (boolean) to keep track of task status
  • Use filters to sort through tasks
  • Directly update tasks when needed

The main idea here is to start by organizing your data well. Then, use array methods to handle that data effectively. Keeping things organized, using functions to manage your arrays, and knowing how to access and update data can help make your apps strong and efficient.

Common Pitfalls and How to Avoid Them

Troubleshooting

When you're working with arrays in TypeScript, sometimes things don't go as planned. Here are some tips to help you avoid common mistakes and fix them if they happen:

Index Out of Bounds Errors

Sometimes, you might try to get something from an array using a number (index) that doesn't exist in the array:

let fruits = ['Apple', 'Banana'];
let fruit = fruits[3]; // Oops, there's no item at index 3

Prevention Tips:

  • Always check how many items are in the array before you try to get something using an index.
  • Remember, the last item is always array.length - 1.
  • Make sure the index you're using is correct.

Troubleshooting:

  • Use try/catch blocks around code where you're not sure if the index exists.
  • Always check if the index is valid by comparing it to the array's length.

Incorrect Array Types

It's common to accidentally add something of the wrong type to an array that's supposed to have only one type of item:

let fruits: string[] = ['Apple', 'Banana'];
fruits.push(5); // Error, you can't add a number to a string array

Prevention Tips:

  • Be clear about what type of items your array should have from the start.
  • Use .filter to clean your data before adding it to the array.
  • If your array can have items of different types, use a union type like (number|string)[].

Troubleshooting:

  • Use try/catch to catch type errors.
  • Before adding an item, check its type with typeof.
  • Give clear error messages if there's a type mismatch.

Confusing Array Declaration

TypeScript offers a few ways to declare arrays, which can sometimes be confusing:

let arr1 = []; // This can hold any type
let arr2: string[] = []; 
let arr3: Array<string> = []; 

Prevention Tips:

  • Choose one way of declaring arrays and stick with it for consistency.
  • Use comments to explain your choice and what type of items the array holds.

Troubleshooting:

  • Double-check the types you've declared and make sure they match what you intended.
  • Decide on the best way to declare arrays in your code and use it consistently.

By following these tips, you can avoid most common mistakes with arrays in TypeScript. Remember to always validate your data and have a plan for handling errors.

Further Resources

Continuing Your Journey

After learning about arrays in TypeScript, here are some next steps to keep improving:

Official Documentation

The TypeScript team has detailed guides on arrays:

Community Resources

Here are some easy-to-follow guides on arrays:

For questions or help, the TypeScript Discord and StackOverflow are good places to start.

Online Courses

If you like learning through videos, here are a couple of suggestions:

These resources and courses are great ways to get better at using arrays in TypeScript. If you have more questions, don't hesitate to ask.

Conclusion

Arrays are super important when you're dealing with data in TypeScript. They help you keep your data neat and tidy, and make it easier to work with.

Here's what you should remember:

  • Arrays let you put a bunch of related things under one name. This is way simpler than trying to keep track of lots of different things on their own.
  • Using things like string[] or Array<number> helps make sure all the stuff in your array is the same type, which means fewer mistakes.
  • TypeScript has some cool shortcuts like map, filter, reduce, and forEach that can do a lot of the heavy lifting for you, so you don't have to write the same code over and over.
  • You can also put more complicated stuff in arrays, like objects or even arrays inside of other arrays, to keep things organized.
  • It's important to handle mistakes the right way, check that you're using the right types of data, and stick to good practices to avoid problems with arrays.

The best way to get good at using arrays is just to use them. Start with the basics and try out different methods.

When you're working on projects, look for places where it makes sense to group data together. Anytime you need data to be in order, or organized, that's a great chance to use an array in TypeScript.

And if you ever get stuck, there's plenty of help out there to keep you going. Just stay curious, keep trying things out, and learn from any mistakes.

Happy coding!

What are the basics of array?

Think of an array as a shelf where you can line up books of the same kind. In TypeScript, arrays help you organize things like numbers or words in a neat row. Each thing on the shelf (or element in the array) has a special spot called an index, starting with 0 for the first item.

To make an array in TypeScript, you use square brackets [] and can say what type of things it will hold with a colon :. For example:

let numbers: number[] = [1, 2, 3];

This means you have a shelf called numbers that's only for number items.

Some key points about arrays:

  • They start counting at 0
  • You can change items using their spot number
  • You can keep many related things together
  • Use methods like push() to add items or pop() to take them out
  • Transform arrays with methods like map(), filter(), and reduce()

How do you define an array in TS?

In TypeScript, there are two main ways to set up arrays:

  • With square brackets, sometimes adding a type:
let arr = [1, 2, 3]; 
  • Using Array<type> syntax:
let arr: Array<number> = [1, 2, 3];  

The second way is good for making sure your array only has the type of things you want. You can also use a shortcut like this:

let arr: number[] = [1, 2, 3];

This makes it clear the array is just for numbers.

How to get first 5 elements of array in TypeScript?

To grab the first 5 things from an array, you can use the .slice() method like this:

let arr = [1, 2, 3, 4, 5, 6, 7, 8];

let firstFive = arr.slice(0, 5); 

.slice() picks out a part of the array, starting at one spot and ending before another. So firstFive will have [1, 2, 3, 4, 5].

What is an array for dummies?

An array is like a box where you can store several items that are all the same type, kind of like a bunch of apples or a collection of coins. For example:

let fruits = ['Apple', 'Banana', 'Orange']; 

This fruits array is a place to keep different fruit names together.

Here's what to remember about arrays:

  • They help you keep related things together in order
  • Adding or removing items is easy
  • You find items by their number in the line, starting with 0
  • They're meant for holding things that are all one type, like all numbers or all strings
  • They're great for grouping stuff together and going through each item one by one

So, you can think of an array as a neat list that keeps all your items organized!

Related posts

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more