Language: EN

typescript-arrays

Using Arrays in TypeScript

In TypeScript, an array is a ordered collection of elements, which can be of any type (although they are usually homogeneous).

TypeScript provides several ways to declare and manipulate arrays, making data collection handling quite comfortable and straightforward.

There are two main syntaxes for declaring an array in TypeScript. The most common is using brackets ([]), as follows.

let numeros: number[] = [1, 2, 3, 4, 5];
let palabras: string[] = ["TypeScript", "JavaScript", "Node.js"];

Alternatively, we can use the Generic Class Array<T>

let numeros: Array<number> = [1, 2, 3, 4, 5];
let palabras: Array<string> = ["TypeScript", "JavaScript", "Node.js"];

Generally we will use the first, except in some advanced cases (like factories) where we will need to use the second

Multidimensional Arrays

Multidimensional arrays (matrices) can be declared by nesting arrays.

let matriz: number[][] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

Iterating Over Arrays

TypeScript supports iteration using traditional loops and the for...of syntax.

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

for (let num of numeros) {
    console.log(num);
}

In addition, we have the forEach method, which is an Array method that serves the same purpose (we will see it in the next section)

Array Methods and Properties

TypeScript inherits array methods and properties from JavaScript, so we have a large number of functions available to manipulate and operate with arrays.

:::::::

Practical Examples

Finding Duplicate Elements

function encontrarDuplicados(arr: number[]): number[] {
    let duplicados: number[] = [];
    let contador: { [key: number]: number } = {};

    arr.forEach((num) => {
        contador[num] = (contador[num] || 0) + 1;
    });

    for (let num in contador) {
        if (contador[num] > 1) {
            duplicados.push(Number(num));
        }
    }

    return duplicados;
}

let numeros: number[] = [1, 2, 3, 4, 5, 2, 3, 4];
console.log(encontrarDuplicados(numeros));  // [2, 3, 4]

Sorting an Array of Objects

interface Persona {
    nombre: string;
    edad: number;
}

let personas: Persona[] = [
    { nombre: "Luis", edad: 25 },
    { nombre: "Ana", edad: 22 },
    { nombre: "Luis", edad: 30 }
];

personas.sort((a, b) => a.edad - b.edad);
console.log(personas);
// [
//     { nombre: "Ana", edad: 22 },
//     { nombre: "Luis", edad: 25 },
//     { nombre: "Luis", edad: 30 }
// ]