Language: EN

typescript-arrays

Using Arrays in TypeScript

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

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

There are two main syntaxes to declare 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 one, except in some advanced cases (like factories) where we will need to use the second one.

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);
}

Additionally, we have the forEach method, which is an Array method that serves the same function (we will see it in the next section).

Array Methods and Properties

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

  • length: Returns the number of elements in the array.
let numeros: number[] = [1, 2, 3, 4, 5];
console.log(numeros.length);  // 5
  • push(...elements): Adds one or more elements to the end of the array.
numeros.push(6);
console.log(numeros);  // [1, 2, 3, 4, 5, 6]
  • pop(): Removes and returns the last element of the array.
let ultimo: number = numeros.pop();
console.log(ultimo);  // 6
console.log(numeros);  // [1, 2, 3, 4, 5]
  • unshift(...elements): Adds one or more elements to the beginning of the array.
numeros.unshift(0);
console.log(numeros);  // [0, 1, 2, 3, 4, 5]
  • shift(): Removes and returns the first element of the array.
let primero: number = numeros.shift();
console.log(primero);  // 0
console.log(numeros);  // [1, 2, 3, 4, 5]
  • slice(start, end?): Returns a shallow copy of a portion of the array.
let subArray: number[] = numeros.slice(1, 3);
console.log(subArray);  // [2, 3]
  • splice(start, numberOfElements, ...elements?): Adds or removes elements from the array.
numeros.splice(2, 1, 99);
console.log(numeros);  // [1, 2, 99, 4, 5]
  • concat(...arrays): Combines two or more arrays.
let otrosNumeros: number[] = [6, 7, 8];
let combinados: number[] = numeros.concat(otrosNumeros);
console.log(combinados);  // [1, 2, 99, 4, 5, 6, 7, 8]
  • forEach(callback): Executes a function for each element in the array.
numeros.forEach((num) => console.log(num));
// 1
// 2
// 99
// 4
// 5
  • map(callback): Creates a new array with the results of calling a function on each element.
let cuadrados: number[] = numeros.map((num) => num * num);
console.log(cuadrados);  // [1, 4, 9801, 16, 25]
  • filter(callback): Creates a new array with all elements that pass a test.
let mayoresQueTres: number[] = numeros.filter((num) => num > 3);
console.log(mayoresQueTres);  // [99, 4, 5]
  • reduce(callback, initialValue?): Applies a function against an accumulator and each value of the array (from left to right) to reduce it to a single value.
let suma: number = numeros.reduce((acumulador, num) => acumulador + num, 0);
console.log(suma);  // 111

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: "Juan", 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: "Juan", edad: 25 },
//     { nombre: "Luis", edad: 30 }
// ]