What is an Array in TypeScript?
An array in TypeScript is a data structure method that holds multiple values of a uniform type in one variable.
For instance, you can create an array of strings, numbers, or even objects.
In addition, an array is a unique kind of data type that can sequentially store numerous values of various data types, utilizing a specific syntax.
Creating Arrays
You can create arrays in two ways in TypeScript.
- By using square brackets.
This is similar to JavaScript. Here’s an example:
let subjects: string[] = ['Programming', 'Math', 'Software Development'];
- By using the Array syntax.
Here’s an example:
let grades: Array = [90, 95, 99 ];
Immutable Arrays:
TypeScript allows you to make arrays immutable using the read-only keyword.
Here’s an example:
const friends : readonly string[] = ["Joseph"];
// pets.push("Bella"); // Error: Property 'push' does not exist on type 'readonly string[]'.
Type Deduction:
TypeScript can deduce the type of an array if it has initial values.
Here’s an example:
const grades = [87, 88, 89]; // TypeScript infers this as number[]
// digits.push("10"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
In TypeScript, you can define an array of objects in several ways.
Here are a few examples:
- Inline typing:
let students: {name: string, age: number}[] = [
{ name: 'Anna', age: 20 },
{ name: 'Bella', age: 22 },
{ name: 'Cassy', age: 21 }
];
console.log(students);
- Using an interface:
interface Student {
name: string;
age: number;
}
let students: Student[] = [
{ name: 'Anna', age: 20 },
{ name: 'Bella', age: 22 },
{ name: 'Cassy', age: 21 }
];
console.log(students);
- Using a type:
type Student = {
name: string;
age: number;
}
let students: Student[] = [
{ name: 'Anna', age: 20 },
{ name: 'Bella', age: 22 },
{ name: 'Cassy', age: 21 }
];
console.log(students);
- Using the built-in Array type:
let students: Array<{name: string, age: number}> = [
{ name: 'Anna', age: 20 },
{ name: 'Bella', age: 22 },
{ name: 'Cassy', age: 21 }
];
console.log(students);
TypeScript Array Methods
The following list enumerates various Array methods that serve diverse functions.
1. concat()
The concat() method is a built-in method of the Array object that allows you to merge two or more arrays into a new array.
Example:
let samplearray1 = [10, 20, 30];
let samplearray2 = [40, 50, 60];
let result = samplearray1.concat(samplearray2);
console.log(result);
Output:
[ 10, 20, 30, 40, 50, 60 ]
2. copyWithin()
This method is used to copy a sequence of array elements within the array.
Example:
Basic implementation of copyWithin() method with two parameters:
const subjects: string[] = ['Math', 'English', 'Programming', 'Science'];
// Copying the element at 3rd position and store it at position 1
subjects.copyWithin(1, 3);
console.log(subjects);
Output:
["Math", "Science", "Programming", "Science"]
3. every()
The every() method is used to check if every element in an array satisfies a certain condition.
Example:
let samplearray: number[] = [11, 20, 33, 40, 55, 60];
let result: boolean = samplearray.every((e: number) => {
return e % 2 == 0;
});
result ? console.log('All numbers are even!') : console.log('All numbers are not even!');
Output:
"All numbers are not even!"
Here’s an example code with objects:
type studentGrade = {
name: string,
grade: number
};
let arr: studentGrade[] = [
{ name: 'Anna', grade: 85 },
{ name: 'Bella', grade: 90 },
{ name: 'Cassy', grade: 95 }
];
let result: boolean = arr.every((e: studentGrade) => {
return e.grade > 10;
});
result ? console.log('All students have grades higher than 80') : console.log('Not all students have grades higher than 96');
Output:
"All students have grades higher than 80"
4. forEach()
The forEach() method is used to execute a function on each item in an array.
Example:
let grades: number[] = [80, 85, 90, 95, 100];
grades.forEach((grades: number) => {
console.log(grades);
});
Output:
80
85
90
95
100
Example with objects:
type Student = {
name: string,
grades: number
};
let people: Student[] = [
{ name: 'Anna', grades: 85 },
{ name: 'Bella', grades: 90 },
{ name: 'Cassy', grades: 95 }
];
people.forEach((person: Student) => {
console.log(person.name + " has " + person.grades + " average.");
});
Output:
Anna has 85 average.
Bella has 90 average.
Cassy has 95 average.
5. indexOf()
The indexOf() method is used to get the index within the calling String object or Array of the first occurrence of the specified value.
Example:
type Grades = number;
let arr: Grades[] = [80, 85, 90, 95, 100];
let index: Grades = arr.indexOf(95);
console.log("index is : " + index);
Output:
index is : 3
6. join()
The join() method is used to join all the elements of an array into a string.
Example:
type Grade = number;
let arr: Grade[] = [80, 85, 90, 95, 100];
let str: string = arr.join(", ");
console.log("String : " + str);
Output:
String : 80, 85, 90, 95, 100
7. indexOf() and lastIndexOf()
Use indexOf() to find the index of the first occurrence of an element in an array. lastIndexOf() does the same but for the last occurrence.
Example:
const numbers = [2, 4, 6, 8, 10, 3, 6];
const firstIndex = numbers.indexOf(3);
const lastIndex = numbers.lastIndexOf(3);
console.log(firstIndex);
console.log(lastIndex);
Output:
5 (firstIndex
5 (lastIndex)
8. toString()
The toString() method is used to convert an array to a string.
Each element is converted to a string and separated by commas.
Example:
const numbers = [2, 4, 6, 8, 10];
const arrayAsString = numbers.toString();
console.log(arrayAsString);
Output:
Output: "2,4,6,8,10"
9. findIndex()
findIndex() returns the index of the first element satisfying a condition. If no element is found, it returns -1.
Example:
const numbers = [2, 4, 6, 8, 10];
const firstEvenIndex = numbers.findIndex(number => number % 2 === 0);
console.log(firstEvenIndex);
Output:
Output: 0
10. fill()
The fill() method changes all elements in an array to a specified value. It’s useful for initializing or resetting array values.
Example:
const filledArray = new Array(5).fill(0);
console.log(filledArray);
Output:
[0, 0, 0, 0, 0]
11. flat() and flatMap()
flat() flattens a nested array structure, and flatMap() maps each element to a new array before flattening.
Example:
const nestedArray = [1, [2, 3], [4, [5]]];
const flattenedArray = nestedArray.flat();
const doubledFlattened = nestedArray.flatMap(num => [num, num * 2]);
console.log(flattenedArray);
console.log(doubledFlattened);
Output:
[1, 2, 3, 4, [5]] (flattenedArray)
[1, 2, 2, 3, 4, 8, [5, NaN]] (doubledFlattened)
12. push() and pop()
Add elements to the end of an array with push(), and remove the last element with pop().
Example:
const numbers = [2, 4, 6, 8, 10];
numbers.push(6);
const removedElement = numbers.pop();
console.log(numbers); // Output: [2, 4, 6, 8, 10, 6]
console.log(removedElement); // Output: 6
Output:
[2, 4, 6, 8, 10, 6]
6
13. shift() and unshift()
Use shift() to remove the first element from an array, and unshift() to add elements to the beginning.
Example:
const numbers = [2, 4, 6, 8, 10];
const firstElement = numbers.shift();
numbers.unshift(0);
console.log(firstElement);
console.log(numbers);
Output:
2
[0, 4, 6, 8, 10]
14. from()
The Array.from() method creates a new array from an array-like or iterable object.
Example:
const iterable = 'hello';
const charArray = Array.from(iterable);
console.log(charArray);
Output:
["h", "e", "l", "l", "o"]
15. keys(), values(), and entries()
These methods return iterators for array keys, values, and key-value pairs, respectively.
Example:
const numbers = [2, 4, 6, 8, 10];
const keysIterator = numbers.keys();
const valuesIterator = numbers.values();
const entriesIterator = numbers.entries();
console.log([...keysIterator]); // Output: [0, 1, 2, 3, 4]
console.log([...valuesIterator]); // Output: [2, 4, 6, 8, 10]
console.log([...entriesIterator]); // Output: [ [0, 2], [1, 4], [2, 6], [3, 8], [4, 10] ]
Output:
[0, 1, 2, 3, 4]
[2, 4, 6, 8, 10]
[ [0, 2], [1, 4], [2, 6], [3, 8], [4, 10] ]
16. forEach() with index and array
The forEach() method also provides access to the current index and the entire array during iteration.
Example:
const numbers = [2, 4, 6, 8, 10];
numbers.forEach((number, index, array) => {
console.log(`Number ${number} at index ${index}`);
});
Output:
Number 2 at index 0
Number 4 at index 1
Number 6 at index 2
Number 8 at index 3
Number 10 at index 4
17. toLocaleString()
The toLocaleString() method is used to convert a number or a date into a string, using the locale settings.
Example:
let num: number = 123456.789;
let str: string = num.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
console.log(str);
Output:
123,456.79
What is the difference between an “array” and a “list” in TypeScript?
The terms “array” and “list” in TypeScript are often used interchangeably, but there are some differences based on the context and the language you’re coming from.
An array in TypeScript is a homogenous collection of elements, meaning all elements in the array are of the same type.
Arrays can be declared in two ways: using square brackets [] or using the generic array type Array.
Once an array is created, its size is set and can’t be changed. Also, you can get to any item in the array fast by using its position number.
TypeScript does not have a built-in List data type like some other languages (e.g., C# or Python).
However, TypeScript arrays are dynamic and provide functionalities similar to a list in other languages.
You can put in or take out items, and the array’s size adjusts on its own.
Conclusion
In this article, we’ve learned that an array in TypeScript is a data structure that stores multiple values of a consistent type within a single variable.
The article highlights the process of creating arrays, their immutability, type inference, and the various methods available for manipulating them.
Furthermore, it delineates the distinction between arrays and lists in TypeScript, underscoring the dynamic nature of arrays as opposed to the fixed size of traditional lists found in other languages.
I hope that this article enhances your understanding of Arrays of Objects in TypeScript.