javascript tutorial - [Solved-5 Solutions] Empty an array - javascript - java script - javascript array



Problem:

Is there a way to empty an array and if so possibly with .remove()?

Solution 1:

If we need to keep the original array because we have other references to it that should be updated too, we can clear it without creating a new array by setting its length to zero:

A.length = 0;
click below button to copy the code. By JavaScript tutorial team

Solution 2:

A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below: A.splice(0, A.length);

Solution 3:

Performance test:

a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length)  // 97% slower
while (a.length > 0) {
    a.pop();
} // Fastest
click below button to copy the code. By JavaScript tutorial team

Solution 4:

We can add this to your JavaScript file to allow your arrays to be "cleared":

Array.prototype.clear = function() {
    this.splice(0, this.length);
};
click below button to copy the code. By JavaScript tutorial team

Then we can use it like this:

var list = [1, 2, 3];
list.clear();
click below button to copy the code. By JavaScript tutorial team

Or if we want to be sure we don't destroy something:

if (!Array.prototype.clear) {
    Array.prototype.clear = function() {
       this.splice(0, this.length);
    };

}
click below button to copy the code. By JavaScript tutorial team

Solution 5:

Array.prototype.clear = function() {
    this.length = 0;
};
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Empty an array