TypeScript -Array

TypeScript Array

TypeScript array is a collection of homogenous/(same datatype) values. In simple word,  typescript  array can store the value of same datatype.

 There are two ways to create/declare an array

Using square brackets([])

Syntax  : let name_of_array:data_type =[v1,v2,v3, ….,vn]

 

let numArrays: number[] = [101,201,301];  // number array 

 

create the array using generic array type(Array<T>) where T donates Datatype   

Syntax : let name_of_array :Array<T> =[v1,v2,v3, ….,vn]

let numArrays:Array<number>=[101,201,301];

 

Features of an Array

  • Array declaration allocates contiguous/sequential memory blocks.
  • Same data type values are stored in an array.
  • Size of the array cannot be changed Once array initialize.
  • Array elements can be accessed using index and index start from 0.
  • It’s also supports two-dimensional array.
  • Array element values can be modified/updated but cannot be removed.

Array Common operations

Create an Array

  

        // Created employees array with 5 values
        let employees : string[]=['John','Mike','Adam','Mona','Jack']

        // console the length of array
        console.log(employees.length);  // 5
    

Access (index into) an Array item

  

        let first_item= employees[0];  // get the first item of array

        let last_item=employees[4];   // get the last item of array

        let last_item_using_length =employees[employees.length -1];     // get the last item of array using array length -1 to get the last index

        console.log(first_item);        //John
        console.log(last_item);         //Jack
        console.log(last_item_using_length);    //Jack
        console.log(employees[5]);      //undefined

    

Loop over an Array

  

        // loop using function
        employees.forEach(function(item,index){
        console.log(`${item} is at ${index} Index`);
        })

        // look using arra
        employees.forEach( (item,index) =>{
        console.log(`${item} is at ${index} Index`);
        })

        // John is at 0 Index
        // Mike is at 1 Index
        // Adam is at 2 Index
        // Mona is at 3 Index
        // Jack is at 4 Index

    

Add to the end of an Array

  

        let employees : string[]=['John','Mike','Adam','Mona','Jack']
        // Add element to array
        employees.push('Harry')
        console.log(employees); //[ 'John', 'Mike', 'Adam', 'Mona', 'Jack', 'Harry' ]

    

Remove from the end of an Array

  

        // Remove element from end
        let employees : string[]=['John','Mike','Adam','Mona','Jack']

        employees.pop()

        console.log(employees); //[ 'John', 'Mike', 'Adam', 'Mona', 'Jack' ]
    

Remove from the front of an Array

  

        // remove 'John' from the starting
        let employees : string[]=['John','Mike','Adam','Mona','Jack']
        employees.shift()
        console.log(employees);  //[ 'Mike', 'Adam', 'Mona', 'Jack' ]
    

Add to the front of an Array

  

        let employees : string[]=['John','Mike','Adam','Mona','Jack']
        // add element 'John' at 0 index
        employees.unshift('John')
        console.log(employees);  //[ 'John', 'Mike', 'Adam', 'Mona', 'Jack' ]

    

Find the index of an item in the Array

  

        let employees : string[]=['John','Mike','Adam','Mona','Jack']
        // find index of a element
        let indexPosition =employees.indexOf('Mike')
        console.log(indexPosition);  //1
    

Property

Description

from() The Array.from() method creates a new Array object from any object using length property or Array type object.
isArray() The Array.isArray() method check whether the passed argument value is an Array or not.
of() The Array.of() method creates a new Array object from a variable number of arguments
concat() The concat() method is used to merge/join two or more arrays and return the new array.
copyWithin() The copyWithin() method copies array items to another position within same array without overwriting the existing values.
entries() The entries() method returns an Array Iterator object with key& value pairs of every index in the array.
every() The every() method verify all the array elements pass a test and return true/false. If all elements pass the provided test return true else false.
fill() The fill() method fills/modifies/replace all the elements of an array with a static value. It returns the updated array.
filter() The filter() method creates an array with all items that pass a test by the provided function.
find()< The find() method returns the first item in the provided array that pass the test.
findIndex() The findIndex() method returns the index of the first item in the array that pass the test. Otherwise return -1
flat() The flat() method creates a new array with all sub-array items concatenated into it.
flatMap() The flatMap() method maps all the elements using a mapping function, then flattens the result into a new array.
forEach() The forEach() method call a provided function once for each array item.
includes() The includes() method check whether an array includes a specified value, returning true or false
indexOf() The includes() method check whether an array includes a specified value, returning true or false
join() Joins all items of an array into a string.
keys() Returns an array Iteration object with containing the keys of original array.
lastIndexOf() Search the array for an item and returns the last index of matched item.
map() Creates a new array with the results of calling a function for each array item.
pop() Removes/Delete the last item from an array.
push() Add new item in array at the end position.
reduce() Reduce the item of an array to a single value from left-to-right.
reduceRight() Reduce the item of an array to a single value from right-to-left.
reverse() Reverses the order of the items in an array.
shift() Remove/delete the first item from an array.
slice() returns the selected item in an array, as a new array.
some() Verify if any of the items in an array passes the test by provided function.
sort() Sorts the items of an array.
splice() Add/delete elements from an array and modify the original array.
toString() Converts an array to a comma separated string.
unshift() Adds new item at 0 position of array.
values() Returns new Array Iteration Object, containing the values of the original array.

1. from()

The Array.from() method creates a new Array object from any object using length property or Array type object.

  

        let str1 ='Hello TypeScript';

        let num_arr=[101,201,301]

        console.log(Array.from(str1));      //output :  [    'H', 'e', 'l', 'l',    'o', ' ', 'T', 'y',    'p', 'e', 'S', 'c',     'r', 'i', 'p', 't']
        console.log(Array.from(num_arr));   //output :  [ 101, 201, 301 ]
    

2. isArray()

The Array.isArray() method check whether the passed argument value is an Array or not.

  

        console.log(Array.isArray({id: 101,name:'John'}));  //output :false
        console.log(Array.isArray('Hello TypeScript'));     // output : false
        console.log( Array.isArray(undefined));             // output : false
        console.log(Array.isArray(true));                   // output : false
        console.log(Array.isArray(null));                   // output : false
    

3. of()

The Array.of() method creates a new Array object from a variable number of arguments

  

        console.log(Array.of(5));                 //output :  [ 5 ]
        console.log(Array.of(101, 201, 301));     //output : [ 101, 201, 301 ]
        console.log(Array(7));                    //output : [ <7 empty items>            ]
        console.log( Array(1, 2, 3));             //output :  [ 1, 2, 3 ]
    

4. concat()

The concat() method is used to merge/join two or more arrays and return the new array.

  

        let emp_arr1 : string[]=['John','Mike']
        let emp_arr2 : string[]=['Adam','Mona','Jack']

        let comcat_arr =emp_arr1.concat(emp_arr2)
        console.log(comcat_arr);    //output :  [ 'John', 'Mike', 'Adam', 'Mona', 'Jack' ]

    

5. copyWithin()

The copyWithin() method copies array items to another position within same array without overwriting the existing values.

  

        let employees : string[]=['John','Mike','Adam','Mona','Jack']
        let employees1 : string[]=['John','Mike','Adam','Mona','Jack']


        let result1 = employees.copyWithin(0,2,4);  // Copy to 0 index start from index 2 and copy till index 4

        let result2 = employees1.copyWithin(0,3); // Copy to 0 index start from index 3 to end of array

        console.log(result1);           // output :  [ 'Adam', 'Mona', 'Adam', 'Mona', 'Jack' ]
        console.log(result2);           // output :  [ 'Mona', 'Jack', 'Adam', 'Mona', 'Jack' ]
    

6. entries()

The entries() method returns object of an Array Iterator with key & value pairs of every items in the array.

  

        let employees : string[]=['John','Mike','Adam','Mona','Jack']
        let iterator1 = employees.entries();

        console.log(iterator1);     // output : Object [Array Iterator] {}

        console.log(iterator1.next().value);  //output :  [ 0, 'John' ]

        console.log(iterator1.next().value); //output :  [ 1, 'Mike' ]

        for(let x of iterator1){

        console.log(x); // console all the key and value
        }

        //output :
        // [ 0, 'John' ]
        // [ 1, 'Mike' ]
        // [ 2, 'Adam' ]
        // [ 3, 'Mona' ]
        // [ 4, 'Jack' ]
    

7. every()

The every() method verify all the array elements pass a test and return true/false. If all elements pass the provided test return true else false.

  

        let num_arr1 =[2,4,6,8,10]
        let num_arr2 =[2,4,6,8,11]

        // check all the numbers are even number and return the true value if condition satisfied
        let result = num_arr1.every( x=> {return x%2 ==0});

        console.log(result);  // output : true

        let result1 = num_arr2.every( x=> {return x%2 ==0});

        console.log(result1); // output : false
    

8. fill()

The fill() method fills/modifies/replace all the elements of an array with a static value. It returns the updated array.

  

        let employees : string[]=['John','Mike','Adam','Mona','Jack']

        let result1 = employees.fill('Luca',3,4)  //  Fill the 'luca' from index 3 until 4

        console.log(result1); // output  :[ 'John', 'Mike', 'Adam', 'Luca', 'Jack' ]

        let result2 = employees.fill('Harry',3)  //  Fill the 'Harry' from index 3 to end of array

        console.log(result2);       // output  :[ 'John', 'Mike', 'Adam', 'Harry', 'Harry' ]

        let result3 = employees.fill('Lisa')    // Fill the 'Lisa to all elements of array

        console.log(result3);       // output  :[ 'Lisa', 'Lisa', 'Lisa', 'Lisa', 'Lisa'
    

9. filter()

The filter() method creates an array with all items that pass a test by the provided function.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result = employees.filter( item => item.length >4) // Filter all the item with length greater than 4

        console.log(result);        // Output : [ 'Michael', 'Oliver' ]
    

10. find()<

The find() method returns the first item in the provided array that pass the test.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result = employees.find( item => item.length >4) // find the first item with length greater than 4

        console.log(result);        // Output : Michael
    

11. findIndex()

The findIndex() method returns the index of the first item in the array that pass the test. Otherwise return -1

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result = employees.findIndex( item => item.length >6) // find the index of item which length has greater than 6

        console.log(result);        // Output : 3
    

12. forEach()

The forEach() method call a provided function once for each array item.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        employees.forEach(item =>{
        console.log(item);
        })

        // Output :
        // John
        // Mike
        // Adam
        // Michael
        // Oliver
    

13. indexOf()

The indexOf() method returns the first index of specified item which isfound in the array, otherwise -1 if it is not present in array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        console.log(employees.indexOf('John'));     // output  : 0

        console.log(employees.indexOf('Adam'));     // output  : 2
        console.log(employees.indexOf('Oliver'));   // output  : 4

        console.log(employees.indexOf('Lisa'));     // output  : -1

    

14. join()

Joins all items of an array with comma separated and return the merged string

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result= employees.join();       // join the array using default separator(',')
        let result1= employees.join('|');   // join the array using passed parameter('|')

        console.log(result);            // outout : John,Mike,Adam,Michael,Oliver
        console.log(result1);           // output : John|Mike|Adam|Michael|Oliver
    

15. keys()

Returns an array Iteration object with containing the keys of original array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let allkeys = employees.keys();
        console.log(allkeys);   // output :  Object [Array Iterator] {}

        for(let key of allkeys){
        console.log(key);
        }

        // output
        // 0
        // 1
        // 2
        // 3
        // 4
    

16. lastIndexOf()

Search the array for an item and returns the last index of matched item.

  

        const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

        console.log(animals.lastIndexOf('Dodo'));
        // expected output: 3

        console.log(animals.lastIndexOf('Tiger'));
        // expected output: 1

    

17. map()

Creates a new array with the results of calling a function for each array item.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result = employees.map(item=>  item)
        console.log(result);

        let  num_arr = [2, 4,9,101 ];
        let result1 = num_arr.map(item => item * 2);
        console.log(result1);

    

18. pop()

Removes/Delete the last item from an array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        console.log(employees);        // output : [ 'John', 'Mike', 'Adam', 'Michael', 'Oliver' ]
        employees.pop() // remove the last item of array 'Oliver'

        console.log(employees);  // output : [ 'John', 'Mike', 'Adam', 'Michael' ]
    

19. push()

Add new item in array at the end position.

  

        console.log(employees);        // output : [ 'John', 'Mike', 'Adam', 'Michael', 'Oliver' ]
        employees.push('Luca')         // add an item to array in last 'Luca'

        console.log(employees);  // output : [ 'John', 'Mike', 'Adam', 'Michael', 'Oliver', 'Luca' ]
    

20. reduce()

Reduce the item of an array to a single value from left-to-right.

  


        let  num_arr = [2, 4,9,101 ];

        // 2+ 4+9+101
        let result = num_arr.reduce( (total,currentValue)=> total + currentValue);
        console.log(result);        // output 116

        let  num_arr1 = [2, 4,9,101 ];

        const sumtotal = (total,currentValue) => total + currentValue;

        // 5+2+ 4+9+101
        let result1 = num_arr1.reduce( sumtotal,5);
        console.log(result1); // output : 121
    

21. reduceRight()

Reduce the item of an array to a single value from right-to-left.

  

        let  num_arr = [2, 4,9,101 ];

        //  101 -9-4-2
        let result = num_arr.reduceRight( (total,currentValue)=> total - currentValue);
        console.log(result);        // output 86

        let  num_arr1 = [2, 4,9,101 ];

        const sumtotal = (total,currentValue) => total - currentValue;

        // 5- 101 -9-4-2
        let result1 = num_arr1.reduceRight( sumtotal,5);
        console.log(result1); // output : -111

    

22. reverse()

Reverses the order of the items in an array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result = employees.reverse();
        console.log(result); //[ 'Oliver', 'Michael', 'Adam', 'Mike', 'John' ]
    

23. shift()

Remove/delete the first item from an array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result = employees.shift();
        console.log(result); // output : John

    

24. slice()

returns the selected item in an array, as a new array.

  

        let employees: string[] = ['John', 'Mike', 'Adam', 'Michael', 'Oliver']

        let result = employees.slice(3);
        console.log(result);        //[ 'Michael', 'Oliver' ]
        let result1 = employees.slice(3, 4);
        console.log(result1);       //  [ 'Michael' ]

        let result2 = employees.slice(1, 4);
        console.log(result2);       //[ 'Mike', 'Adam', 'Michael' ]
    

25. some()

Verify if any of the items in an array passes the test by provided function.

  

        let num_arr1 =[2,4,6,8,10]
        let num_arr2 =[2,4,6,8,11]

        let result = num_arr1.some( x=> {return x%2 ==0});  // checks whether an element is even or not

        console.log(result);  // output : true

        let result1 = num_arr2.some( x=> {return x%2 ==0}); // checks whether an element is even or not

        console.log(result1); // output : false
    

26. sort()

Sorts the items of an array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result = employees.sort();
        console.log(result); // output : [ 'Adam', 'John', 'Michael', 'Mike', 'Oliver' ]
    

27. splice()

Adds/delete elements from an array and modify the original array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']
        let employees1 : string[]=['John','Mike','Adam','Michael','Oliver']

        employees.splice(1,0,'Lisa');
        console.log(employees); // [ 'John', 'Lisa', 'Mike', 'Adam', 'Michael', 'Oliver' ]


        employees1.splice(2,1,'Harry');
        console.log(employees1);   //[ 'John', 'Mike', 'Harry', 'Michael', 'Oliver' ]
    

28. toLocaleString()

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result =employees.toLocaleString()

        console.log(result);  //John,Mike,Adam,Michael,Oliver

    

29. toString()

Converts an array to a comma separated string.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let result =employees.toString()

        console.log(result);  //John,Mike,Adam,Michael,Oliver
    

30. unshift()

Adds new item at 0 position of array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        employees.unshift('Lisa')

        console.log(employees);   //[ 'Lisa', 'John', 'Mike', 'Adam', 'Michael', 'Oliver' ]
    

31. values()

Returns new Array Iteration Object, containing the values of the original array.

  

        let employees : string[]=['John','Mike','Adam','Michael','Oliver']

        let  iterator =employees.values()
        console.log(iterator);     //Object [Array Iterator] {}

        for(let emp of iterator){
        console.log(emp);
        }

        // output
        // John
        // Mike
        // Adam
        // Michael
        // Oliver