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 handling collections of data quite comfortable and straightforward.
If you want to learn more, check out the Introduction to Programming Course
There are two main syntaxes for declaring an array in TypeScript. The most common one uses 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 (such as factories) where we will need to use the second one.
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 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 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(…elementos)
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(…elementos)
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(inicio, fin?)
Returns a shallow copy of a portion of the array.
let subArray: number[] = numeros.slice(1, 3);
console.log(subArray); // [2, 3]
splice(inicio, numElementos, …elementos?)
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 every 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, valorInicial?)
Applies a function to 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
Find 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]
Sort 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 }
// ]
