How to remove an array's element in TypeScript Using Pop()
Overview
We can remove an element of an array in TypeScript using the pop() method. This method removes the last element of the array and returns that element.
Syntax
array.pop()
The syntax for pop() method for an Array in TypeScript
Parameter
array: This is the array whose last element we want to remove.
Return Value
The value returned is the element that was removed.
Example
// create arrays in TypeScriptlet names: string[] = ["Theodore", "James", "Peter", "Amaka"]let numbers : Array<number>;numbers = [12, 34, 5, 0.9]let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]// print previous arraysconsole.log("Previous Arrays")console.log(names)console.log(numbers)console.log(cars)// pop and print last elementsconsole.log(names.pop())console.log(numbers.pop())console.log(cars.pop())// print modified arraysconsole.log("\nCurrent Arrays")console.log(names)console.log(numbers)console.log(cars)
Explanation
- Line 2-5: We create some arrays in TypeScript.
- Line 9-11: We print arrays to the console.
- Line 14-16: Some elements are popped and printed to the console.
- Line 19-22: We then print the modified arrays again to the console.