Coder Perfect

In JavaScript, how can I empty an array?

Problem

Is it possible to empty an array, and if so, could it be done with.remove()?

For instance,

A = [1,2,3,4];

I’m not sure how I’m going to empty that.

Asked by akano1

Solution #1

Clearing an existing array A:

Method 1

(I gave this as my initial response to the inquiry)

A = [];

This code creates a new empty array in variable A. This is ideal if you don’t have any other references to the old array A because it creates a completely new (empty) array. This method should be used with caution since if this array is referenced from another variable or property, the original array will remain unchanged. If you just want to refer to the array by its initial variable A, this is the way to go.

This is also the most expedient option.

This code example demonstrates an issue that can arise while using this method:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Method number two (as suggested by Matthew Crumley)

A.length = 0

The existing array will be cleared by setting its length to 0. Some have suggested that this might not work in all JavaScript implementations, but this is not the case. Because the length property of an array is a read/write property, it also works in ECMAScript 5’s “strict mode.”

3rd method (as suggested by Anthony)

A.splice(0,A.length)

Using.splice() will work properly, but it will really yield a copy of the original array because the.splice() function returns an array with all the removed entries. According to benchmarks, this has no effect on performance.

Method 4 (as tanguy k proposed)

while(A.length > 0) {
    A.pop();
}

In contrast to the prior benchmarks mentioned in the original response, this method is not very succinct, and it is also the slowest.

Performance

Methods 2 and 3 are the most equivalent in performance and are much faster than method 4 when clearing an existing array. Take a look at this benchmark.

The original benchmarks that were used to measure the performance of the four approaches outlined above were faulty, as Diadistis pointed out in their response below. Because the cleaned array was reused in the first iteration, the second iteration included clearing an array that was already empty.

This problem is fixed by running the following benchmark: http://jsben.ch/#/hyj65. Methods #2 (length property) and #3 (splice) are definitely the fastest (apart from method #1, which does not affect the original array).

This has been a heated topic that has sparked a lot of debate. There are several correct answers, and because this answer has been tagged as the approved solution for a long time, I’ll include all of them here.

Answered by Philippe Leybaert

Solution #2

You can clear the original array without making a new one if you need to keep it because you have other references to it that need to be updated as well:

A.length = 0;

Answered by Matthew Crumley

Solution #3

Here the fastest working implementation while keeping the same array (“mutable”):

function clearArray(array) {
  while (array.length) {
    array.pop();
  }
}

While (array.pop()) cannot be simplified: the tests will fail.

Given that Map and Set both have clear(), it would seem sensible to include clear() for Array as well.

TypeScript version:

function clearArray<T>(array: T[]) {
  while (array.length) {
    array.pop();
  }
}

The corresponding tests:

describe('clearArray()', () => {
  test('clear regular array', () => {
    const array = [1, 2, 3, 4, 5];
    clearArray(array);
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });

  test('clear array that contains undefined and null', () => {
    const array = [1, undefined, 3, null, 5];
    clearArray(array);
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });
});

Here’s the latest version of jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152

Offline version of jsPerf. https://jsben.ch/hyj65 is a similar benchmark.

Answered by tanguy_k

Solution #4

Using the splice method to empty the content of the array A, as shown below, is a more cross-browser compatible and optimal solution:

A.splice(0, A.length);

Answered by Anthony

Solution #5

The responses with a total of 2739 upvotes are both deceptive and wrong.

“How do you empty your existing array?” is the inquiry. For example, consider A = [1,2,3,4].

Assume your mother requests that you empty the garbage can.

It’s the simplest thing in the world to empty an array object:

A.length = 0;

As a result, the can under “A” is not only empty, but also spotless!

You were requested to empty it, not the other way around:

A.length = 0;

The only code that successfully empties the contents of a JavaScript array is this one.

Answered by Bekim Bacaj

Post is based on https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript