TypeScript - how to empty array
In this article, we would like to show you how to clear / empty an array in TypeScript.
Quick solution:
array.splice(0, array.length);
Â
There are available following ways to clear the array:
- by setting the empty array as a variable value,
- by setting the array'sÂ
lengthto0, - by using
splice()method, - by using
pop()Â method inÂwhileloop.
Â
1. Setting the empty array as a variable value
In this solution, we set the existing variable to a new empty array.
Runnable example:
let array: number[] = [1, 2, 3];
array = [];
console.log(array.length); // 0
Output:
0
Note:
You should be careful using this method, because if you have referencedarray from another variable or property, the original array will remain unchanged.
2. Setting the array's length to 0Â
In this solution, we empty the existing array by setting its length to 0.
Runnable example:
const array: number[] = [1, 2, 3];
array.length = 0; // <---------- array size reset that clears array
console.log(array.length); // 0
Output:
0
3. Using splice() methodÂ
In this solution we use splice() method to remove every item from the index 0 to array.length.
Runnable example:
const array: number[] = [1, 2, 3];
array.splice(0, array.length); // <---------- removes all items
console.log(array.length); // 0
 Output:
0
Note:
splice()Â method will return an array with all the removed items.
4. Using pop() method in while loopÂ
In this solution we use while loop to pop() every single item from an array.
Runnable example:
const array: number[] = [1, 2, 3];
while (array.length > 0) {
array.pop(); // <---------- each iteration removes one item
}
console.log(array.length); // 0
 Output:
0
Note:
This solution is the slowest from all of the above.Â