{

Frequently Used Array Examples - Javascript|Typescript


In this blog post, We are going to learn Array Examples in typescript and javascript

Frequently Used Array  Examples - Javascript|Typescript

The array is a collection of elements/objects stored under one name. The size of the array is fixed. As you know there are requirements to find out elements in an array of typescripts.

You can check my post on Array Sort-Object Examples

Typescript Examples | Javascript Examples

Following is a list of frequently used array examples

How to remove an element or object from the Array

This example shows how to

  • Delete / remove element from an array using Array.prototype.splice function
  • First find an index of an element in an array using findIndex() function
  • remove element from array using splice() function
var arrayStrings = new Array("one", "two", "there", "four");   
var deleteElement = "one";  
let index = this.arrayStrings.findIndex(d => d === deleteElement);   
this.arrayStrings.splice(index, 1);  
console.log(arrayStrings );  

Output is

  
0: "two"  
1: "there"  
2: "four"  

How to Create a Statically typed array of functions or callbacks

This example shows

  1. How to Create an array of interfaces
  2. How to create a Type array of callbacks or functions

First Create a named function of an interface that accepts strings and returns a void Create an array of interfaces

interface MyInterface {  
    (name: string): void;  
}  
var mycallback: MyInterface[] = [];  
console.log(mycallback)  

Or We can also use a typed array literal syntax for creating an array of functions

  
var myNewFunction: { (name: string): void; } [];  

How to retrieve the last element or object from an array

This example shows

  • the last element of an array using an array.length-1 function
  • How to find the length of an array using Array.length-1 element
  • Get the Last element of an array | array.pop() method
var arrayStrings = new Array("one", "two", "there", "four");   
console.log(arrayStrings[arrayStrings.length-1] );  
console.log(arrayStrings.pop() );  

Output is

four  
four  

How to create a Static array in typescript class

This example shows

  1. Create a Static private array of a class
  2. the getSize method returns the static array size using the length function
class MyClass {  
    private static stringArray: string[] = ["one", "two", "three","four"];  
    getSize(): number {  
        return MyClass.stringArray.length;   
    }  
}  
var myobject = new MyClass();  
console.log(myobject.getSize());  

Output is

3  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.