Typescript array [Complete Tutorial with Examples]

This typescript tutorial will see how we can tackle the array with typescript, and what array is in typescript, how we can declare an array in typescript. And also we will cover the below scenario of the typescript array:

  • What is Typescript array
  • typescript array of objects
  • typescript array destructing
  • typescript array type
  • typescript array of strings
  • typescript array contains
  • typescript array find
  • typescript array filter
  • typescript array length
  • typescript array map
  • typescript array reduce
  • typescript array of arrays
  • Typescript array index
  • typescript array append
  • typescript array add object
  • typescript array delete
  • typescript array concat
  • typescript array as constant
  • typescript array at
  • typescript array any match
  • typescript array clear
  • typescript array empty
  • typescript array count
  • typescript array contains object
  • typescript array constructor
  • typescript array comparison
  • typescript array distinct
  • declare interface typescript array

What is a Typescript array

A user-defined data type is an array. A contiguous memory area with a homogenous collection of items of similar types that may hold numerous values of various data types is known as an array.

An array is a data structure that contains items of comparable data types and is also considered an object. We can only hold a fixed set of elements and cannot increase its size once it is defined.

The array uses index-based storage. i.e., the first member of an array is stored at index 0 or index I while the following items are kept at index ‘i+1.’

Features of an array

  • Sequential memory blocks are allocated by an array declaration.
  • An array is static. This indicates that an array cannot be resized once it has been started.
  • An array element is represented by each memory block.
  • A distinct number known as the subscript or index of the element is used to identify array items.
  • Arrays must also be defined before usage, much like variables. An array can be declared using the var keyword.
  • Initializing an array means adding elements to it.
  • Values for array elements can be changed or altered but not removed.

Declaring and initializing an array

Here we will see how we can declare and initialize an array with typescript.

Use the following syntax to define and initialize an array in Typescript:

//declaration
var arrayName [: data type];

//initialization
arrayName = [val1, val2, val3]

Without specifying a data type, an array declaration is assumed to be of type any. Such an array’s type may be determined during initialization by looking at the data type of the array’s first item.

For example: var arr : number[]=[1,2,3,4]

Read Typescript filter array

Typescript array of objects

Here we will see an example array of objects with typescript.

The Array object can also be used to generate an array. It is possible to pass the Array constructor.

  • A numerical value that indicates the array’s size or
  • A collection of values separated by commas.

Here you can see an example of a typescript array of objects.

var arrNames:number[] = new Array(4)  

for(var j = 0;j<arrNames.length;j++) { 
   arrNames[j] = j * 2 
   console.log(arrNames[j]) 
}

And run the above code in the code editor by creating an app.ts file. Then run the code by using the below command:

ts-node app.ts

Next, you can see the below output in the console:

0
2
4
6

Typescript array destructuring

Here we will see an example of a typescript array destructuring.

Refers to the process of breaking an entity’s structure. When used inside the context of an array, TypeScript enables destructuring.

Example of typescript array destructing

In the code editor, create a new file named app.ts file, then write the below code:

var country:string[] = ['USA',"UK"] 
var[a,b] = country 
console.log(a) 
console.log(b)

Now to run the above code, you can use the below command, also you can see the app.js file generated.

ts-node app.ts

Next, you can see the below output, in your console.

USA
UK
Typescript array destructuring
Typescript array destructuring

Typescript array type

Here we will see how we can define typescript array type

TypeScript, like JavaScript, supports the use of arrays of values. There are two ways to write array types. In the first case, you use the element type followed by [] to represent an array of that element type:

let array: number[]= [12,13,14]

In the second case, we will declare using a generic array type Array<data type>:

let names: Array<String>=["Aman", "Alex"];

Typescript array of strings

Here we will see an example of a typescript array of strings.

As we know, an array is a data type that can store many values of various data types.

Now let’s see an example of how we can define the string data type with a typescript array.

let names : string[]=["Alex", "Aman","Mike"]

or

let names: Array<string>=["Alex","Aman", "Mike"]

Read Typescript hello world program for beginners

Typescript array contains

Here we will see an example of an array contains in Typescript.

The array contains is a method in typescript which checks whether an array contains the specific element or not. This is a TypeScript array method that returns true if the array contains the specified element and false otherwise.

Because TypeScript is comparable to JavaScript, array methods will be identical as well, with the main difference being syntax or notation. The array includes a function in JavaScript that is the same as it is in TypeScript.

The syntax of the typescript array contains:

Array.includes(element, start)

This is the way for searching for specific values in an array. This procedure will be passed on two arguments.

  • element: Required argument indicating the element to be searched for.
  • start: It is an optional parameter with the default value of 0, indicating the point in the array where the search should begin.

Returns a true or false Boolean result.

Example 1: We will create an array of the country names, and we will check whether the array is available or not.

In the code editor, create an app.ts file, and then write the below code:

var country:string[] = ['USA',"UK"] 
 
console.log("Country name is present:", country.includes("USA"));

To compile and get the output, you can run the below command:

ts-node app.ts
Typescript array contains
Typescript array contains

Example 2: Here we will see whether the list of countries contains the USA or not.

In the app.ts file write the below code, which will check the USA is not.

const country: string[] = ['USA', 'UK', 'India'];

if (country.includes('USA')) {
  console.log('βœ… USA is contained in list');
} else {
  console.log('⛔️ USA is NOT contained in list');
}

Now run the above code, using the below command, and you can see the result.

ts-node app.ts
 array contains in typescript
array contains in typescript

Read Typescript Identifiers and Keywords

Typescript array find

Here we will see how we can use array.find in typescript.

The find() method in typescript returns the first member in the specified array that meets the testing function. Undefined is returned if no values satisfy the testing function.

Example: Find an element from an array

In the app.ts file write the below code, to get the first element, which is greater than 15.

const num = [6, 18, 20, 30, 44];

const findNum = num.find(elem => elem > 15);

console.log(findNum);

To compile the above .ts file, run the below command, and you can see the below result as 18.

ts-node app.ts
Typescript array find
Typescript array find

Example 2: Find an object in an array

In the app.ts file write the below code, to find an object from an array.

const emp = [
    { id: 1, employeeName: 'Alex' },
    { id: 2, employeeName: 'Aman' },
    { id: 3, employeeName: 'John' },
  ];
  
  // πŸ‘‡οΈ const findId2: {id: number; employeeName: string; } | undefined
  const findId2 = emp.find((obj) => {
    return obj.id === 2;
  });

console.log(findId2);

Now run the below command to compile the code, and you can see the output.

ts-node app.ts
Typescript find object in an array
Typescript find object in an array

Typescript array filter

Here we will see how we can use the filter method in a typescript.

The filter() method returns a new array containing all items that pass the test defined by the given function.

Syntax:

array.filter(callback [, thisObject])

Callback- function for parameter details that performs tests on each element.

thisObject-This object will be used as this when the callback is executed.

For example: filter the words from an array, whose length is greater than 5.

const words = ['fun', 'limitless', 'elite', 'exhaust', 'typescript', 'javascript'];

const output = words.filter(word => word.length > 5);

console.log(output);

Now, compile the above code, run the below command and you can see the output:

ts-node app.ts
Typescript array filter
Typescript array filter

Read Typescript type annotation

Typescript array length

Here we will see how we can use the array. length in typescript.

The length property in the typescript array, use to get the number of elements available in an array.

For example: calculate the length of an array

In the app.ts file write the below code, to get the number of elements available in an array:

const num = [6, 18, 20, 30, 44];

console.log("The numbber of element in an array : " + num.length);

Now to compile the above code, run the below command and you can see the output in the console.

ts-node app.ts
Typescript array length
Typescript array length

Typescript array map

Here we will see an example of an array map method in typescript.

In typescript, the array.map method is an in-built function that is used to create a new array, with the output of calling a provided function on every item in this array.

The syntax for the array.map:

array.map(callback[,  thisObject])

Map methods accept two parameters:

  • callback: This argument is the function that generates an item of the new Array from an item of the existing one.
  • thisObject: This option specifies the Object that will be used as this when the callback is executed.
  • return: This function returns the array that has been constructed.

For example : We will see how we can use map method.

In the app.ts file, write the below code to add the two mapped values.

var num = [2, 4, 6, 10, 18, 20];

	var newnum = num.map(function(val, index){
	
	console.log("key : ",index, "value : ",val+val);
	})

Now to compile the code and run the below command and you can see the result.

ts-node app.ts
Typescript array map
Typescript array map

Read TypeScript Enum

Typescript array reduce

Here we will see how to use array reduce method in typescript.

The reduce() method applies a function to two array values (from left to right) at the same time in order to reduce them to a single value.

Syntax:

array.reduce(callback[, initial value]);

Parameter

  • callback- Function that will be called for each value in the array.
  • initialValue – Object to pass as the first parameter to the callback’s first call.

For example:

In the code editor, write the below code, by using array.reduce we will reduce the array into single value.

 var total = [1, 2, 4, 5].reduce(function(a, b){ return a + b; }); 
    console.log("total is : " + total );

Now, to compile the above code, run the below command and you can see the below output.

ts-node app.ts
Typescript array reduce
Typescript array reduce

Typescript array of arrays

Here we will see an example of array of array and multidimensional in typescript.

An array element’s value can be derived from another array in typescript. Such arrays are known as multidimensional arrays. Multi-dimensional arrays are supported by TypeScript. A two-dimensional array is the most basic version of a multi-dimensional array.

Declare 2D array with typescript

Syntax:

var arrName: datatype[][]= [ [val1,val2,val3],[v1,v2,v3] ]

Access 2D array element in an array

Here is how we can 2D array element in an array, by referencing the below code:

var arrName:datatype[initialArrayIndex][referencedArrayIndex] = [ [val1,val2,val 3],
   [v1,v2,v3] ]

Example of Multiple array

In the app.ts file write the below code to get the value of arrays of arrays.

 var multArray:number[][] = [[3,4,5],[20,25,26]]  
console.log(multArray[0][0]) 
console.log(multArray[0][1]) 
console.log(multArray[0][2]) 
console.log(multArray[1][0]) 
console.log(multArray[1][1]) 
console.log(multArray[1][2])

Now to compile the above code, write the below command, and you can see the below output.

ts-node app.ts
Typescript array of arrays
Typescript array of arrays

Typescript array by index

Here we will see how we can use indexOf method to get the index of an item

The indexOf() function in typescript returns the first index in the array at which a specified element can be found, or -1 if it does not exist.

Syntax of indexOf()

array.indexOf(searchElement[, fromIndex]);

Parameter used:

searchElement- Element to be found in the array.

fromIndex : The index from which to start the search. If set to 0, the whole array will be searched. If the index is larger than or equal to the array’s length, -1 is returned.

This method will return the index of an item.

Example:

Open the code editor, create the app.ts file write the below code:

var index = [16, 23, 5, 180, 40].indexOf(180); 
console.log("index is : " + index );

To compile the code, run the below command and you can see the result.

ts-node app.ts
Typescript array index
Typescript array index

Typescript array append

Here we will see how we can append the item to the array in typescript.

The push() function appends the specified item(s) to the end of the array and returns the new array’s length.

Syntax

array.push(element1, ..., elementN);

Parameter

element1, …, elementN βˆ’ The elements to add to the end of the array.

Return value: The length of the new array

Example: Here we will see how we can append the number to an array of numbers.

In the app.ts file, you can write the below code, to append the number in an array.

var num = new Array(5, 14, 7); 
var length = num.push(11); 
console.log("new numbers is : " + num );  
length = num.push(22); 
console.log("new numbers is : " + num );

Now to compile the code, using the below command and you can see the output in the console.

ts-node app.ts
Typescript array append
Typescript array append

Typescript array add object

Here we will see how we can add the object to an array, by using the push method in typescript.

As we already discuss the push method, so now we will see an example of how we can add the object to an array in typescript.

const arr: { name: string; age: number; department:string }[] = [];

arr.push({ name: 'Tom', age: 30, department:"IT" });

console.log(arr); // πŸ‘‰οΈ [{ name: 'Tom', age: 30, department:"IT" }]

Now to compile the code, you can run the below command and you can see the result in the console.

ts-node app.ts
Typescript array add
Typescript array add

Typescript array delete

Here we will see how we can remove items from an array in typescript.

Example 1: Remove items from an array in the typescript

To remove the element from an array we will use the splice method in typescript.

The splice method modifies the original array’s contents by deleting, altering, or adding new items and returns an array containing the deleted elements.

Splice syntax in an array:

array.splice(index, howMany, [element1][, ..., elementN]);

In this syntax:

  • index -The index at which to initiate changing the array.
  • howMany- An integer specifying the number of old array items to delete. If howMany is 0, no items are eliminated.
  • element1,…, elementN- The items to be added to the array. Splice merely eliminates the items from the array if no items are specified.

Now let’s see an example of how we can delete an item from an array using splice.

In the app.ts file, write the below code to remove the items from the list.

const country: string[] = ['UK', 'USA', 'Russia', 'Africa'];

const index = country.indexOf('Russia');
console.log(index); // πŸ‘‰οΈ 2

if (index !== -1) {
  country.splice(index, 1);
}

// πŸ‘‡οΈ ['UK', 'USA', 'Africa']
console.log(country);

Now, run the below command, to compile the above code, you can see the below output.

ts-node app.ts
Remove elements from an array in the typescript
Remove elements from an array in the typescript

Example 2: Remove an Object from an Array in TypeScript

In this example, we will see how to remove an object from an array using the splice method in typescript. In the app.ts file, write the below code to remove an object from an array.

const info: { id: number, name:string }[] = [{ id: 1 , name:"Alex" }, { id: 4, name:"John" }, { id: 8, name:"Ron" }];

const indexOfObject = info.findIndex((object) => {
  return object.id === 8;
});

console.log(indexOfObject); // πŸ‘‰οΈ 2

if (indexOfObject !== -1) {
  info.splice(indexOfObject, 1);
}

// πŸ‘‡οΈ [ { id: 1, name: 'Alex' }, { id: 4, name: 'John' } ]
console.log(info);

Now to compile the above code run the below command, and you can see the below output in your console:

Remove an Object from an Array in TypeScript
Remove an Object from an Array in TypeScript

Example 3: Remove the last item from an Array with typescript

To remove the last element from an array, we will use the pop method in typescript. Then this method returns the last element from an array and also the length of the array changes.

Now let’s see an example of how we can remove the last items from an array using the typescript pop method.

const country: string[] = ['UK', 'USA', 'Russia', 'Africa'];

const removed = country.pop();
console.log(removed); // πŸ‘‰οΈ Africa

// πŸ‘‡οΈ [ 'UK', 'USA', 'Russia' ]
console.log(country);

Now to compile the above code, run the below command and you can see the output in the console.

ts-node app.ts
Remove an last item, from an Array in TypeScript
Remove an last item, from an Array in TypeScript

Example 4: Remove the first item from an array in typescript

To remove the first item from an array, we will use the shift method in typescript. And it returns the removed item, i.e. first item from an array.

Now let’s see an example of how we can use the Shift method in typescript to remove the first item from an array. So in the app.ts file write the below code:

const country: string[] = ['UK', 'USA', 'Russia', 'Africa'];

const removed = country.shift();
console.log(removed); // πŸ‘‰οΈ UK

// πŸ‘‡οΈ [ 'USA', 'Russia', 'Africa' ]
console.log(country);

To compile the above code, run the below command and you can see the output in the console:

ts-node app.ts
Remove an first item, from an Array in TypeScript
Remove an first item, from an Array in TypeScript

Example 5: Delete items from an array that doesn’t satisfy the condition

To delete/ remove items from an array that doesn’t satisfy the condition, for this we will use the below code:

const country: string[] = ['UK', 'USA', 'USA', 'Africa'];

const newArr: string[] = country.filter((element) => {
  return element !== 'USA';
});

// πŸ‘‡οΈ [ 'UK', 'Africa' ]
console.log(newArr);

Now to compile the above code run the below command and you can see the output in the console.

Delete items from an array that doesn't satisfy the condition
Delete items from an array that doesn’t satisfy the condition

These are examples of how we can remove elements from an array.

Typescript array concat

Here we will discuss how to use the contact() method in TypeScript.

The concat() method in TypeScript creates a new array by joining an array with one or more than one array.

Here is the syntax of using the concat() method in TypeScript.

Array.concat(val_1, val_2, …., val_N)

In the syntax, val_1, val_2, and val_N represent one or more than one array which we want to concat with the Array.

Now that we have seen the syntax of using the concat() method, let us discuss an example.

In the app.ts file write the below code, to concat two arrays and get the result by

var countries_1 = ["USA", "UK", "Canada"];
var countries_2 = ["Australia", "New Zealand"];


var total_countries = countries_1.concat(countries_2);
console.log("Array of Count : " + total_countries );
Typescript array concat
Typescript array concat

Typescript array as constant

Here we will see how we can define a const array in typescript.

In typescript to declare a const array, use a const assertion, such as const arr = [10, 5] as const. With const assertation we can set the element as read-only, signifying to the language that the type in the expression will not be expanded (e.g. from [1, 2] to number[]).

const num= [20, 4] as const;
function multiply(x: number, y: number) {
  return x * y;
}

console.log(multiply(...num)); // πŸ‘‰οΈ 80

To compile the below code, we will run the below command, and you can see the output in the console.

ts-node app.ts
Typescript array as constant
Typescript array as constant

But if we will try to update the array’s contents, you will get an error because we are using constants, so the contents in an array will remain constants.

Typescript array at

Here we will see how we can use the Typescript array at method.

The at () in typescript accepts an integer value and it returns the element at that index, which allows positive and negative integers, as negative integers are counted back from the last element in the array.

This method returns the item in the array matching the given index.

Syntax of typescript array at:

at(index)

Now let’s see an example of how we can use a typescript array at the method. So in the app.ts file write the below code to see the element at the given index.

const country: string[] = ["USA", "UK","UAE","Africa", "India"];

let index = 3;

console.log(`Using an index of ${index} the item returned is ${country.at(index)}`);
// πŸ‘‰ output: Africa

index = -4;

console.log(`Using an index of ${index} item returned is ${country.at(index)}`);
// πŸ‘‰ output: UK

Now to compile the above code run the below command and you can see the output in the console.

ts-node app.ts
Typescript array at
Typescript array at

Typescript array any match

Here we will see how we can use some() to match any element in an array.

The some() in typescript checks whether at least one item from an array member satisfies the test defined by the given function. It returns true if it gets an element in the array for which the specified function returns true; otherwise, it returns false. It makes no changes to the array.

Syntaxs of Typescript some()

some((element) => { /* … */ })
some((element, index) => { /* … */ })
some((element, index, array) => { /* … */ })

// Callback function
some(callbackFn)
some(callbackFn, thisArg)

// Inline callback function
some(function (element) { /* … */ })
some(function (element, index) { /* … */ })
some(function (element, index, array) { /* … */ })
some(function (element, index, array) { /* … */ }, thisArg)

Now, let’s see an example how we use the some () in an typescript array. In the app.ts file write the below code.

const array = [11, 12, 31, 42, 50];

// checks whether an element is even
const even = (element:number) => element % 2 === 0;

console.log(array.some(even));
// πŸ‘‰ output: true

Now, compile the below code by using the below command and you can see the result in the console:

ts-node app.ts
Typescript array any match
Typescript array any match

Typescript array clear

Here we will see different methods how we can clear an array in typescript

Here we will discuss the different ways to clear an array in typescript:

  • By putting the array’s length to 0
  • Using splice() method
  • Using pop() method

By setting the array’s length to 0

To set the length of an array as length 0 or clear an array:

  • Set the length to 0.
  • When the length property is updated, all items with indexes greater than the length are removed automatically.

In the code editor, create app.ts file, and write the below code:

const num= [12,14,16,18]
num.length=0;
console.log(num);

Now compile the above code and run the below command and you can see the output in the console.

ts-node app.ts
Typescript array clear
Typescript array clear

Using splice() method

To clear the content in an array in typescript, we will use the splice(), inside this method we will define start index as 0, this will clear the array.

So in the app.ts file write the below code to clear an array with splice method.

const num= [12,14,16,18]
num.splice(0);
console.log(num);

To compile the above code run the below command and you can see the output in the console.

ts-node app.ts
clear array in typescript
clear array in typescript

Using pop() method

To clear an array in typescript using the pop(), we will do:

  • Using a for or while loop, iterate through an array.
  • To delete an element from an array, use the Array.pop() function.
  • When the loop finishes, all of the elements in the array are eliminated.

Let’s see an example, in the app.ts file, write the below code to clear an array in typescript.

const num= [12,14,16,18]
while(num.length){
	num.pop()
}
console.log(num);

To compile the code and run the below command and you can see the output in the console.

ts-node app.ts
typescript array can be empty
typescript array can be empty

Typescript array empty

Here we will see how we can declare an array as empty in typescript.

In TypeScript to empty an array, reassign the array variable and set it to an empty array, for example, arr = []. You can only reassign variables that have been defined with the let and var keywords. In TypeScript, this is the most efficient approach to empty an array.

Let’s see an example of how we can empty an array in typescript. In the app.ts file write the below code, which will return an empty array.

var num= [12,14,16,18]
num = [];
console.log(num);

To compile the above code and run the below command, you will get an output in the console.

ts-node app.ts
Typescript array empty 1
Typescript array empty

Typescript array count

Here we will see how to count the occurrence of the number of elements in an array in typescript.

To count every occurrence of an item in an array, for this we will use the for-loop. Whereas with for loop, we will loop through an array. With for-loop we can loop through each element in an array, which will count the occurrence of the number of elements in an array in typescript.

Let’s see an example of how many times a single item appears in an array. To do so, we must first set the counter variable to 0, then loop through the array, increasing the number by one each time we locate the element we are seeking for. When we loop over the full array, the counter will record the number of times the item we were looking for appeared. In the app.ts file write the below code:

const allEmpId = [18, 22, 18, 19, 16, 18, 19, 21, 24];
let target = 18;

let counter = 0;
for (let empId of allEmpId) {
  if (empId == target) {
        counter++;
    }
};

console.log(counter); //πŸ‘‰ output: 3

Now to compile the below code, run the below command and you can see the output in the console.

ts-node app.ts
Typescript array count
Typescript array count

Typescript array contains an object

Here we will see an example of different ways how we can check array contains an object in typescript. Here are the methods to check an array contains an object

  1. With array.some method
  2. With array.findIndex method
  3. with array.filter method

To check array contains an object with the array. filter method in typescript

  • On the array, we will call the Array.filter method.
  • Check whether each object in the array has a property in the particular value.
  • This method will return an array in typescript having the objects that satisfy the condition.

Let’s see an example to apply these steps to get the result.

In the app.ts file write the below code to check the array contains an object.

const emp = [
	{id: 10, name: 'John'},
	{id: 20, name: 'Adam'},
  ];
  
  const filteredArray = emp.filter(elem => {
	if (elem.id === 10) {
	  return true;
	}
  
	return false;
  });
  
  console.log(filteredArray); // πŸ‘‰οΈ output: [ { id: 10, name: 'John' } ]
  
  if (filteredArray.length > 0) {
	// πŸ‘‰οΈ object is in the array
	console.log(emp.length) //πŸ‘‰οΈ output:2
  }

To compile the code run the below command and you can see the result in the console.

ts-node app.ts
Typescript array contains an object with array.filter
Typescript array contains an object with array.filter

To check array contains an object with the array. findIndex method in typescript

  • On the array, we will call the Array.findIndex method.
  • Check whether each object in the array has a property in the particular value.
  • This method will return an array of the index or else it will return the -1 if the object is not found in the array

Let’s see an example to apply these steps to get the result.

In the app.ts file write the below code to check the array contains an object.

const emp = [
	{id: 10, name: 'John'},
	{id: 20, name: 'Adam'},
  ];
  
  const index = emp.findIndex(elem => {
	if (elem.id === 20) {
	  return true;
	}
  
	return false;
  });
  
  console.log(index); // πŸ‘‰οΈ output: 1
  
  if (index !== -1) {
	// πŸ‘‰οΈ object is in the array
	console.log(emp.length) //πŸ‘‰οΈ output:2
  }

To compile the code and run the below command and you can see the result in the console.

ts-node app.ts
Typescript array contains an object with array.findIndex
Typescript array contains an object with the array.findIndex

To check array contains an object with the array. some methods in typescript

  • On the array, we will call the Array.filter method.
  • Check whether each object in the array has a property in the particular value.
  • This method will return true if the object is there in the array else it will return false in typescript.

Let’s see an example to apply these steps to get the result.

In the app.ts file write the below code to check the array contains an object.

const emp = [
	{id: 10, name: 'John'},
	{id: 20, name: 'Adam'},
  ];
  
  const isthere = emp.some(elem => {
	if (elem.id === 20) {
	  return true;
	}
  
	return false;
  });
  
  console.log(isthere); // πŸ‘‰οΈ output: true
  
  if (isthere) {
	// πŸ‘‰οΈ object is in the array
	console.log(emp.length) //πŸ‘‰οΈ output:2
  }

To compile the code run the below command and you can see the output in the console.

ts-node app.ts
Typescript array contains an object with array.some
Typescript array contains an object with array.some

Typescript array constructor

Here we will see how to use an array constructor in typescript.

Array constructor in typescript is used to create an Array of objects

Syntax:

new Array(element0, element1, /* … ,*/ elementN)
new Array(arrayLength)

Array(element0, element1, /* … ,*/ elementN)
Array(arrayLength)

For example, we will create an array constructor with multiple parameters. In the app.ts file write the below code:

const country = new Array("USA", "UK","UAE");

console.log(country.length); // 3
console.log(country[0]); // "USA"

To compile the above code, and run the below command, and you can see the result in the console.

ts-node app.ts
Typescript array constructor
Typescript array constructor

Typescript array comparison

Here we will see how we can compare two arrays in typescript.

To compare to arrays in typescripts we will use the below methods

  • Comparing two arrays by converting to string
    • Use json.stingify
    • Use .toString
  • Compare two values by looping through an array
    • using every method
    • using forloop

Comparing two arrays by converting to string

To compare two arrays, a typical and basic way is to first convert them to string form.

You have two options: we will use the JSON.stringify() function in typescript to convert your array to JSON text, or you can use the.toString() method in typescript to return your array as a string.

Use json.stingify

The json.stingify method in typescript is used to serialize an array by converting the array to a string in JSON.

Let’s see an example of json.stingify, to compare two arrays in typescript.

let set1  = [11, 22, 33];
let set2 = [11, 22, 33];

console.log(JSON.stringify(set1) === JSON.stringify(set2)); //πŸ‘‰οΈ output:true

To compile the above code, run the below command and you can see the output in the console.

Typescript array comparison
Typescript array comparison

Use .toString

The .toString method in typescript is used to convert the data type of an array into string, also with this method we can convert an object to string .

Let’s see an example of .toString, to compare two arrays in typescript. In the app.ts file write the below code :

let set1  = [11, 22, 33];
let set2 = [11, 22, 33];

console.log(set1.toString ===set2.toString); //πŸ‘‰οΈ output:true

To compile the code, run the below command and you can see the output in the console.

Typescript array comparison with tostring method
typescript array equality

Compare two values by looping through an array

A better way would be to check the length of the array before looping over and comparing each item of the array.

Using Every method

The every() method allows you to run a function on each element of an array. The call back function is the name given to this function. It has access to several fundamental parameters such as the element, index, and many more.

Syntax:

array.every((currentValue, index, arr)=> { ... }

Let’s see an example, to use every method in typescript, to compare two arrays. In the app.ts file, write the below code:

const compareArrays = (x:any, y:any) =>
  x.length === y.length &&
  x.every((element:number, index:number) => element === y[index]);

let set1 = [11, 22, 33];
let set2 = [21, 22, 23];
let set3 = [11, 22, 33];

console.log(compareArrays(set1, set2)); //false
console.log(compareArrays(set1, set3)); //true

To compile the above code run the below command and you an see the result in the console.

Typescript array comparison with every method
Typescript array comparison with every method

Using for loop

The another method to compare an array, through iteration, using for loop, for each, or map() alongside if statements.

Let’s see an example of for loop in typescript, to compare the two array. In the app.ts file write the below code:

const compareArrays = (x:any, y:any)  => {
	if (x.length !== y.length) return false;
	else {
	  // Comparing each element of your array
	  for (var i = 0; i < x.length; i++) {
		if (x[i] !== y[i]) {
		  return false;
		}
	  }
	  return true;
	}
  };
  let set1 = [21, null, 33];
  let set2 = [21, 22, 23];
  let set3 = [21, undefined, 33];
  let set4 = [21, 22, 23];
  
  console.log(compareArrays(set1, set2)); //πŸ‘‰οΈ output:false
  console.log(compareArrays(set1, set3)); //πŸ‘‰οΈ output:false
  console.log(compareArrays(set2, set4)); //πŸ‘‰οΈ output:true

To compile the above code, run the below command and you can see the result in the console.

ts-node app.ts
Typescript array comparison with for loop
Typescript array comparison with for loop

Typescript array distinct

Here we will see an example to get the distinct value from an array in typescript.

As there is no distinct method is available, so we will use the filter method to get the distinct values from an array.

To filter duplicate items from an array we will use filter method to check only, if the index of the current item of an array is equal to first index of the item in the array, and only add item if it have.

Let’s see an example, to get distinct/unique values from an array using filter method.

const duplicateValues = [11, 12, 22, 11, 12, 22, 41, 50, 41];
const distinctArray = duplicateValues.filter((n, i) => duplicateValues.indexOf(n) === i);
console.dir(distinctArray); //πŸ‘‰οΈ output:[ 11, 12, 22, 41, 50 ]

To compile the below code and run the below command, you can see the output in the console.

ts-node app.ts
Typescript array distinct
Typescript array distinct

Declare interface typescript array

Here we will see an example how to declare interface in typescript array of objects.

To establish an interface for an array of objects, declare the interface for each object’s type and set the array’s type to Type[], for example, const arr: Employee[] = []. All objects added to the array must comply to the type, otherwise the type checker will show error.

Let’s see an example how we can declare interface for array of objects in typescript. In the app.ts file write the below code:

interface Emp {
	EmpId: number;
	EName: string;
  }
  
  const arr: Emp[] = [
	{ EmpId: 1, EName: 'Tom' },
	{ EmpId: 2, EName: 'Jeff' },
  ];
  console.log(arr); //πŸ‘‰οΈ output:[ { id: 1, name: 'Tom' }, { id: 2, name: 'Jeff' } ]
  
  //  Objects with extendable type
  interface Extendable {
	id: number;
	name: string;
	[key: string]: any; // πŸ‘ˆοΈ index signature
  }
  
  const arr2: Extendable[] = [
	{ id: 1, name: 'Tom' },
	{ id: 2, name: 'Jeff', salary: 100 },
  ];

  console.log(arr2);//πŸ‘‰οΈ output:[ { id: 1, name: 'Tom' }, { id: 2, name: 'Jeff', salary: 100 } ]
  

To compile the above code, run the below command and you can see the output in the console.

ts-node app.ts
Declare interface typescript array
Declare interface typescript array

Conclusion

This typescript tutorial, we have gone through different scenario/ examples how one can use an array in typescript. So here are the topics we executed:

  • What is Typescript array
  • typescript array of objects
  • typescript array destructing
  • typescript array type
  • typescript array of strings
  • typescript array contains
  • typescript array find
  • typescript array filter
  • typescript array length
  • typescript array map
  • typescript array reduce
  • typescript array of arrays
  • Typescript array index
  • typescript array append
  • typescript array add object
  • typescript array delete
  • typescript array concat
  • typescript array as constant
  • typescript array at
  • typescript array any match
  • typescript array clear
  • typescript array empty
  • typescript array count
  • typescript array contains object
  • typescript array constructor
  • typescript array comparison
  • typescript array distinct
  • declare interface typescript array
>