TypeScript Array
Arrays in typescript are of fixed-length and homogeneous collection of values very similar to other programming languages. A typescript array can store multiple values of the same data types sequentially.
Arrays are always of fixed size. An array, once it is created, cannot be resized. Individual elements at various positions in the array are accessed via their index .
In this tutorial, we will learn to create an array, clone an array, merge arrays and iterate through the elements of an array in TypeScript with easy-to-follow examples.
Like JavaScript, TypeScript has an Array type to allow the assignment of multiple values. The array is specified by adding a square bracket [] after the type.
To use the type-safety capability of TypeScript, we can add diamond brackets to specify the type of elements in the array. Every time a new value is added to such a generic array, the compiler checks for type compatibility and alerts if there is a type mismatch.
The following example declares a boolean array and then initializes its values.
//Various ways to declare a typed array let myArr1: boolean[]; let myArr2: boolean[] = []; let myArr3: boolean[] = new Array(); let myArr4: boolean[] = Array(); //Initializing an array myArr1 = [false, false, true];
We can declare and initialize the array in the same line.
let flags: boolean[] = [false, false, true]; //or let flags: Array = [false, false, true];
2. Adding an Item to Array
The push() method appends the given value at the last of an array and returns the size of the new array created as a result of push() operation.
It helps in treating the arrays as dynamic lists.
//array of numbers let scores: number[] = [10, 20, 30, 40]; scores.push( 50 ); //[10, 20, 30, 40, 50] scores.push( 'abc' ); //data.ts(24,14): error TS2345: Argument of type '"abc"' is not //assignable to parameter of type 'number'.
3. Iterating Through Array Items
We can use either of for loops to iterate over array elements.
let scores :number[] = [10, 20, 30, 40]; for (var score of scores) < console.log(score); //Outputs 10 20 30 40 >
DO NOT use “for…in” loop which is used to iterate over object attributes.
3.2. Using Traditional for Loop
let scores :number[] = [10, 20, 30, 40]; for (var i = 0; i < scores.length; i++) < console.log(scores[i]); //Outputs 10 20 30 40 >
Use spread operator to clone the array. It is the easiest and the most recommended way.
let origScores: number[] = [10, 20, 30]; let clonedScores: number[] = [. origScores]; console.log(clonedScores); //[10, 20, 30] origScores.push( 40 ); console.log(origScores); //[10, 20, 30, 40] is "changed" console.log(clonedScores); //[10, 20, 30] is "unchanged"
Use spread operator for merging arrays as well. It’s the simplest and most recommended way.
let scores1: number[] = [10, 20, 30]; let scores2: number[] = [40, 50, 60]; let mergedScore = [. scores1, . scores2]; console.log(mergedScore); //[ 10, 20, 30, 40, 50, 60 ]
Drop me your questions in the comments section.
TypeScript – How to Add Items to Array
An array in TypeScript, once initialized, cannot be resized. The items in an array can be modified but cannot be removed (or added) without creating a new array.
So there are essentially two approaches to removing an item from an array:
- Setting the element null/undefined without resizing the array.
- Remove the element and create a new array of remaining elements.
Add, append, or push new items into an array in TypeScript. Also, learn to append or merge an array into a specified array with examples.
let array: number[] = [1, 2, 3]; //Append at the end array.push(4); //[1, 2, 3, 4] //Append at the beginning array.unshift(0); //[0, 1, 2, 3, 4] //Append at specified index array.splice(0, 0, -1, -2); //[-1, -2, 0, 1, 2, 3, 4] //Append a new array let newArray = array.concat([5, 6]); //[-1, -2, 0, 1, 2, 3, 4, 5, 6] //Merge arrays using spread operator let mergedArray = [. array, . [5, 6]]; //[-1, -2, 0, 1, 2, 3, 4, 5, 6]
In TypeScript, like JavaScript, arrays are homogenous collections of values. We can define an array in the following ways. First, we can declare and initialize the array in the same line:
let array: number[] = [1, 2, 3]; let array: Array = [1, 2, 3]; let array:number[] = new Array(1, 2, 3);
Or, we can declare an array and populate it later.
let array:number[] = new Array(3); for(let i = 0;i
2. Add Items at End using array.push()
The array.push() method appends the given items in the last of the array and returns the length of the new array.
newLen = array.push(item1, . itemN);
Let us see an example of adding new items to the array.
let array: Array = [1, 2, 3]; let newLength = array.push(4, 5, 6); console.log(newLength); //6 console.log(array); //[1, 2, 3, 4, 5, 6]
3. Add Items at Start using array.unshift()
The array.unshift() method appends the specified items at the beginning of the array and shifts the existing items to the right.
Let us see an example of unshifting the array items.
let array: Array = [1, 2, 3]; let newLength = array.unshift(-1, 0); console.log(newLength); //5 console.log(array); //[-1, 0, 1, 2, 3]
4. Merging Two Arrays into a New Array
If we have two arrays and want to combine them into a new array containing items from both arrays in a similar order, then we can merge the arrays in the following ways.
The first method uses the spread operator (…). The spread operator is used to expand or spread an iterable or an array.
let array1: number[] = [1, 2]; let array2: number[] = [3, 4]; let mergedArray: number[] = [. array1, . array2]; console.log(mergedArray); // [1, 2, 3, 4]
Another way to merge two arrays is by using the array.concat() method. The concat() method returns a new array comprised of given array joined with other specified array(s) and/or value(s).
let array1: number[] = [1, 2]; let array2: number[] = [3, 4]; let mergedArray: number[] = array1.concat(array2); console.log(mergedArray); // [1, 2, 3, 4]
5. Adding Items at Specified Index Position
Sometimes, we will need to add the new items in an array at the specified index position. We can use the array.splice() method for this purpose. The syntax of splice() method is:
array.splice(index, countOfElemsToDelete, [element1 . elementN]);
- index − Index at which to start changing the array.
- countOfElemsToDelete − An integer indicating the number of elements to remove. Pass 0 not to remove any of the existing elements.
- [element1, . elementN] − An optional list of elements to add to the array from the index location passed as the first argument.
In the following example, we are adding new elements from index location 2.
let array: number[] = [0, 1, 4, 5]; array.splice(2, 0, 2, 3); console.log(array); //[0, 1, 2, 3, 4, 5]
This typescript array tutorial taught us to add new items to an array using different methods. We learned to add items at the beginning, at the end and at any specified index location. We also learned to merge two arrays to produce a new array of combined items from both arrays.
How to add elements to an Array in TypeScript
push method of array is used to add or append elements to the end of an array. This method adds items to the end of an array and returns the length.
In this post, we will learn how to use the push method with example.
Definition of push method:
push method is defined as like below:
Where, e1, e2, etc. are elements to append to the array. This method appends these elements to the end of the array.
Return value of push:
push method returns the length of the newly created array.
Example of push method:
This is the same method available in JavaScript array. In TypeScript also, we can use this method in a similar way.
Let me show you an example:
let arr : string[] = new Array('one', 'two', 'three');console.log('Given array: ',arr);let len = arr.push('four');console.log('Length returned by push: ',len);console.log('New array: ',arr);If you run this program, it will print the below output:
Given array: [ 'one', 'two', 'three' ]Length returned by push: 4New array: [ 'one', 'two', 'three', 'four' ]
- arr is the original array. We are using push to add one string to the array.
- The first log is printing the given array.
- The second log is printing the length that is returned by the push method. It is 4, i.e. the length of the newly created array.
- The third log is printing the newly created array.
Example 2: push with multiple elements:
We can also use push with more than one elements. Let's try to add 3 elements to the array using push:
let arr : string[] = new Array('one', 'two', 'three');console.log('Given array: ',arr);let len = arr.push('four', 'five', 'six');console.log('Length returned by push: ',len);console.log('New array: ',arr);Given array: [ 'one', 'two', 'three' ]Length returned by push: 6New array: [ 'one', 'two', 'three', 'four', 'five', 'six' ]As you can see, the returned length is 6, i.e. the length of the new array.