Skip to main content

TypeScript Arrays

In Typescript, array is a collection of homogeneous element. That element are similar type and store by sequentially order.

Array Declaration

There are two ways to declare typescript arrays. This are syntactically different but provide similar functionality.

var num : number[]; //Array of number type
var str : string[]; //Array of string type 
//Other Way
var num :Array<number>;
var str: Array<string>;

Array Initialization

//Define array of number elements
var amount: number[]=[10,70.2,9.3,100];
var num : Array<number> = [1,3,6,8];

//Define array of string elements
var animal : string[]=["Cat","Dog","Duck","Monkey"];
var fruits : Array<string> = ["Apples","Mango","Orange"];
Array Initialization In typescript
[ 10, 70.2, 9.3, 100 ]
[ 1, 3, 6, 8 ]
[ 'Cat', 'Dog', 'Duck', 'Monkey' ]
[ 'Apples', 'Mango', 'Orange' ]

Accessing Array Element

Array elements are access by index position. And array index are start with zero.

let day: string[] = [
    "Sunday", 
    "Monday", 
    "Tuesday", 
    "Wednesday", 
    "Thursday", 
    "Friday", 
    "Saturday"
]; 
console.log(day);
let size = day.length;
// Display the array elements by using For loop
for(var i = 0; i < size; i++)
{
    // Access Index element
    console.log(day[i]);
}
[ 'Sunday',
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday' ]
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Multi Type Arrays

TypeScript Array Methods

Method Overview
array.push() Added single or multiple elements at the end
array.pop() Remove last element of arrays, and returning that value
array.shift() Remove first element of arrays, and returning that value
array.concat() Combining of two or more array elements and returning this new array
array.copyWithin() Copies specified array elements within the array
array.fill(element) fill (set) a new element value to every element of array
array.filter() This method are create new array under the course condition
array.indexOf() Finding the array element by value, and returns its index. if element not exists then provides -1.
array.join() Combines of all array element into a string
array.includes() Check If an array is contains specific value element
array.lastIndexOf() Returns the last index of an element in the array.
array.unshift() Adds a single or multiple elements at the beginning of array.
array.sort() Sort array elements.
array.reverse() Reverse the order of an array elements.
array.toString() Converting array element into an string and return that result.
array.splice() Adds or removes elements from the array.

push() method

push() method are used to add new element into the end of array. This method are accept one parameter value, This value can be form of a single element, an array and variable length argument. When that is form of multiple element then that are separated by (,) comma.

// Create Array of 4 elements
var arr : number[] = [10, 1, 2, 3];
console.log("A : ",arr);

// Add a single element at the end
arr.push(4); 
console.log("B : ",arr);

// Add multiple element into end
arr.push(5,6); 
console.log("C : ",arr);
A :  [ 10, 1, 2, 3 ]
B :  [ 10, 1, 2, 3, 4 ]
C :  [ 10, 1, 2, 3, 4, 5, 6 ]

pop() method

pop() method are remove one element into last of array and this method are return this deleted element. In case array are no element then this method is returning a undefined.

// Create Array of 4 elements
var arr : number[] = [1, 2, 3, 5];
console.log("A : ",arr);

// Remove last element
var value : number = arr.pop(); 
console.log("B : ",arr, "Remove",value);

// Remove last element
value = arr.pop(); 
console.log("C : ",arr, "Remove",value);
A :  [ 1, 2, 3, 5 ]
B :  [ 1, 2, 3 ] Remove 5
C :  [ 1, 2 ] Remove 3

shift() method

shift() method are remove one element into beginning of array and this method are return this deleted element. In case array are no element then this method is returning a undefined. That is reversal version of pop() method.


var element : (number | undefined);
// Create Array of 3 elements
var arr : number[] = [1,2,3];

console.log("Array : ",arr);
// Remove first element of arr
element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);

// Remove first element of arr
element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);

// Remove first element of arr
element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);


// first case when array is empty
element = arr.shift();
console.log("Remove Element : ",element);
console.log("Array : ",arr);
Array :  [ 1, 2, 3 ]
Remove Element :  1
Array :  [ 2, 3 ]
Remove Element :  2
Array :  [ 3 ]
Remove Element :  3
Array :  []
Remove Element :  undefined
Array :  []

concat() method

This method are used to combine two or more arrays.

var a : Array<any>    = [1,2,3];
var b : Array<string> = ["one","two","three"];
var c : Array<boolean> = [true,false];
var d : Array<any>    = a.concat(b,c);

// Display given values
console.log("A : ",a);
console.log("B : ",b);
console.log("C : ",c);
console.log("D : ",d);
A :  [ 1, 2, 3 ]
B :  [ 'one', 'two', 'three' ]
C :  [ true, false ]
D :  [ 1, 2, 3, 'one', 'two', 'three', true, false ]

copyWithin() method

The copyWithin() method are used to copy sub array and replace with other location in same array. This method are not modify the length of actual array.

fill() method

The fill() method is used to change the value of an array in a given range. This function takes three parameters. The first parameter indicates the specified value. And the second parameter indicates the starting point and the third parameter indicates the end point.

 arrayName.fill(value,startIndex,endIndex);

Here second and third parameters are optional. When provide one parameter to fill function is set given value to each element of array.

var record : number[] = [1,2,3,4,5,6,7,8];

// Actual Array
console.log("A",record);
// Set zero
record.fill(0);
console.log("B",record);

// Set 10 to index 0,1,2
record.fill(10,0,3);
console.log("C",record);

// Set 20 after index 2
record.fill(30,3);
console.log("C",record);
A [ 1, 2, 3, 4, 5, 6, 7, 8 ]
B [ 0, 0, 0, 0, 0, 0, 0, 0 ]
C [ 10, 10, 10, 0, 0, 0, 0, 0 ]
C [ 10, 10, 10, 30, 30, 30, 30, 30 ]

When the first and second parameters provide. Then here the first indicates the set value and the second parameter indicates the starting point to fill the value. And assigns the value from the starting point to the end of the array.

filter() method

The filter() method are used to create new array by using test condition. This test conditions can be function or expression which are apply to calling array. For example.

function evenNumber(value : number)
{
    return (value % 2 == 0);
    
}
function oddNumber(value : number)
{
    return (value % 2 != 0);
}

var record : number[] = [1,4,0,9,11,-2,6, 5];
// Collecting even elements
var even   : number[] = record.filter(evenNumber);
// Collecting odd elements
var odd    : number[] = record.filter(oddNumber);

// Display values
console.log("Record",record);
console.log("Even number",even);
console.log("Odd number",odd);
Record [ 1, 4, 0, 9, 11, -2, 6, 5 ]
Even number [ 4, 0, -2, 6 ]
Odd number [ 1, 9, 11, 5 ]

indexOf() method

This method are return an element of given index in case given element are not valid then this method is returning the value of -1.

var record : number[] = [10,1,20,3,4,5];

// Element 20 are exists at index 2
console.log(record.indexOf(20)); // 2

// Element 32 are not exists -1
console.log(record.indexOf(32)); // -1

join() method

Combines of all array element into a string.

var record: any[] = [1,2,true,3,4,"hello"];

// Separated by underscore
var text : string = record.join("_");
// Array element
console.log(record);
// Display text value
console.log(text);
[ 1, 2, true, 3, 4, 'hello' ]
1_2_true_3_4_hello

includes() method

This method are check array element are exist or not exist. if element is exist then this method are returning the true value otherwise returning the false value.

var record : number[] = [1,2,3,4,5];

// Test 
console.log(record.includes(1));
console.log(record.includes("one"));
console.log(record.includes(3));
console.log(record.includes(33));
true
false
true
false

lastIndexOf() method

The lastIndexOf() method are search given pattern value and return the position of last occurring element.

unshift() method

The unshift() The method is used to insert a new element in the initial state. This method can add one or more elements. And returns the new length.

var arr : number[] = [1,2,3];

console.log("A : ",arr);

// Add a single element 
arr.unshift(4); 
console.log("B : ",arr);

// Add multiple element into Beginning
arr.unshift(5,6); // Add Two element in this case
console.log("C : ",arr);

arr.unshift(7,8,9);
console.log("D : ",arr);
A :  [ 1, 2, 3 ]
B :  [ 4, 1, 2, 3 ]
C :  [ 5, 6, 4, 1, 2, 3 ]
D :  [ 7, 8, 9, 5, 6, 4, 1, 2, 3 ]

sort() method

This method sorts the array of a string element in a sorted order. This method conversion is based on string values.

// Case A sort string
var record : string[] = ["Blueberries", "Apricots", 
                        "Mango", "Avocado", 
                        "Cherries", "Grapes"];

console.log("Before sort",record);
// Sort string
record.sort();
console.log("After sort",record);

function sortNumber(a:number,b:number)
{
    return a-b;
}

// Case B sort number
var num : number[] = [4,-2,52,12,7];
console.log("Before sort",num);
// Sort number
num.sort(sortNumber);
console.log("After sort",num);
Before sort [ 'Blueberries',
  'Apricots',
  'Mango',
  'Avocado',
  'Cherries',
  'Grapes' ]
After sort [ 'Apricots',
  'Avocado',
  'Blueberries',
  'Cherries',
  'Grapes',
  'Mango' ]
Before sort [ 4, -2, 52, 12, 7 ]
After sort [ -2, 4, 7, 12, 52 ]

reverse() method

This method are reversed an existing array.

var record : number[] =[1,2,3,4,5];

console.log("Before ",record);
// Reverse record element
record.reverse();
console.log("After ",record);
Before  [ 1, 2, 3, 4, 5 ]
After  [ 5, 4, 3, 2, 1 ]

toString() method

This method is used to represent an array elements with a string.

var record : number[] =[10,20,30,40,90];

console.log("record ",record);

var text : string = record.toString();

console.log("text ",text);
record  [ 10, 20, 30, 40, 90 ]
text  10,20,30,40,90

splice() method

The splice() method are used to get portion of given index. That is an very important method which is create new array. slice() method are used to copy array elements and this method are return a new array.

var a : number[] = [6,5,4,3,2,1];

// Assign reference
var b : number[] = a;


// Copy array a
var c : number[] = a.slice();

// change array b
b[0] = 100;

console.log("Array a : ",a)
console.log("Array b : ",b)
console.log("Array c : ",c)
Array a :  [ 100, 5, 4, 3, 2, 1 ]
Array b :  [ 100, 5, 4, 3, 2, 1 ]
Array c :  [ 6, 5, 4, 3, 2, 1 ]

Other example.

var record : number[] = [6,5,4,3,2,1];

// Creating a new array from the second index to the end index
var t1 : number[] = record.slice(2);

// Creating a new array using last three element
var t2 : number[] = record.slice(-3);


// Creating a new array from index [1..3]
var t3 : number[] = record.slice(1,3);


// Display array elements
console.log(t1);
console.log(t2);
console.log(t3);
[ 4, 3, 2, 1 ]
[ 3, 2, 1 ]
[ 5, 4 ]




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment