Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

For instance,

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

How can I empty that?

share|improve this question
81  
Please accept a different answer, the accepted answer is just wrong –  Juan Mendes Nov 5 '12 at 20:44
1  
I agree - I have typically used the A = [] method before finding this thread, but I almost continued doing my normal thing until I saw @Daniel's highly rated comment on the currently accepted answer –  phatskat Jan 19 at 21:01
 
Without more context from the OP, who knows which answer is best. Questioners, please make a bit more effort! 'Is it possible to empty with .remove()?' What? And what is the use case? Everyone is arguing over the answer; I have no idea why the question has so many upvotes. –  FizzyTea Jul 7 at 2:19
 
This question (as well as the answer) has so many upvotes because people try the accepted answer and it seems to work, even though it most certainly does not do what the question requests. Because it seems to work the newer programmers are delighted to have found what seems to be the answer so easily and quickly that they click upvote on both the question and the answer. Make no mistake, Daniel Baulig is right in his highly voted comment in the accepted answer. This is why I don't always go for the accepted answer, but the highest voted one, which is clearly Mathew Crumley's answer. –  VoidKing Oct 16 at 15:36
add comment

10 Answers

up vote 280 down vote accepted

Very simple:

A = [];

EDIT

A little extra explanation is required here. The code above A = [] will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array.

However (as other have pointed out below) if you have references to this array, you can empty the original array by setting its length to 0 or by calling .splice() on the array.

Setting the length to zero is the most efficient solution, but this could create problems in some implementations of Javascript (although I don't know of any).

Using .splice() as in A.splice(0,A.length) will work, but it's not very efficient because the .splice() function will return an array with all the removed items, so it will return a copy of the original array in some (most?) Javascript implementations.

So the preferred way to clear an existing array is:

 A.length = 0;

(Matthew Crumley's answer to this question is probably the best one)

share|improve this answer
392  
this will NOT empty the array, but create a new, empty array. This might cause problems, especially if there are other references to the array. OP: Please consider to accept Matthew's answer instead. It is the cleaner and formally correct approach. –  Daniel Baulig Jan 19 '11 at 13:08
16  
To all commenters and downvoters: you are all right, and the answer below (setting the length to 0) is a better answer, but in many cases the solution I presented works perfectly and is more succinct –  Philippe Leybaert Oct 14 '11 at 19:12
6  
arr = new Array() is exactly the same as arr = [] –  Philippe Leybaert May 16 '12 at 12:32
20  
-1: There is a significant difference between emptying an array and creating a new one (as stated by @DanielBaulig). –  David Faivre Aug 19 '12 at 23:16
5  
This does not clear the array. Simply replaces it with a blank one. The problems with this is that any other reference to this variable will still retain the uncleared Array. –  Shamasis Bhattacharya Sep 26 '12 at 12:22
show 6 more comments

How about the below modified version of Jan's initial suggestion?

var originalLength = A.length;
for(var i = originalLength; i > 0; i--) {
     A.pop();
}
share|improve this answer
add comment

According to jsperf a fast solution would be to pop/shift each Array Element in a for-loop.

var originalLength = A.length;
for(var i = 0; i < originalLength; i++) {
    A.pop();   //or .shift();
}

For reference: Link obsolete. See below.

Edit: The solution was incorrect. Please refer to the solution of tanguy_k for the fastest and correct way to empty an array.

share|improve this answer
1  
Nice test, thanks! In IE10 (which is orders of magnitude slower in all tests), array.length = 0; is fastest. –  Greg Woods Apr 11 at 12:55
 
I will confirm that array.pop() is the fastest method on Chrome 27. –  Michael Calvin Jun 6 at 21:03
10  
This only pops half of the elements in the array, since A.length is decreasing as i is increasing. –  755 Jun 25 at 17:10
add comment

Answers from Jan and David McCurley are incorrect!

As noted by 755 in a comment, the algorithm provided by Jan only removes half of the items from the array.

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

Array.prototype.clear = function() {
  while (this.length > 0) {
    this.pop();
  }
};

And the test that goes with it:

describe('Array', function() {
  it('should clear the array', function() {
    var array = [1, 2, 3, 4, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });
});

Here the updated jsPerf: http://jsperf.com/array-destroy/32

share|improve this answer
1  
TT your answer is the only one that correct and fast ( at the same time ) but have some much less "upvotes". Well, it seems that people like pretty solutions that are slow :/ –  Ai_boy Jun 26 at 5:09
 
This is the correct and fastest solution, referred to you in my answer. –  Jan Jun 27 at 9:08
 
Wow, never though I'd see people waging wars over it. I'm going with your solution, thanks. –  S.O. Jul 3 at 14:23
 
@naomik But this is one of the basic functionalities, which should have been there by default. –  thefourtheye Aug 19 at 4:43
1  
@thefourtheye Good solution for performance, though I agree with @naomik, you should not modify native objects. Saying that it should be there is beside the point, the problem is you're modifying globals, which is bad. If you're providing your code for others to use, then it should have no unforeseen side effects. Imagine if another library also modified the Array.prototype and it was doing something slightly different, then all throughout your code [].clear() was slightly wrong. This would not be fun to debug. So, the general message is: Don't modify globals. –  jpillora Sep 14 at 10:39
show 2 more comments

The fastest solution for all current browsers is to implement the pop or shift method. Combining answers from 'leech' and 'jan', we can come up with a method that is declared once and makes it easy to clear the array:

Array.prototype.clear = function()  //Add a new method to the Array Object
{
    var i;
    for(i=0;i<this.length;i++)
    {
        this.pop();
    }
}

var NumberList = new Array();  //Declare the variable
NumberList.push(111);          //Add number to the end of the list
NumberList.clear;              //Clear the list
share|improve this answer
1  
This answer is wrong since Jan implementation is, as 755 said: "only pops half of the elements in the array, since this.length is decreasing as i is increasing" and I've verified this myself –  tanguy_k Jun 25 at 20:09
2  
Please don't encourage modification of the native objects. –  naomik Jul 7 at 6:54
add comment

The simplest way to delete all content of Array is to set length to zero.

Eg. var myArray = ['A','B','C'];

myArray.length = 0; // Delete all content of Array
share|improve this answer
 
Cool! Just like this answer dated Aug 5 '09. –  Scotty.NET 2 days ago
add comment
Array.prototype.clear = function()
{
    this.length = 0;
};

and call it: array.clear();

=)

share|improve this answer
7  
Please don't encourage modification of the native objects. –  naomik Jul 7 at 6:53
 
why do people have this tendency to grab the accepted answer and put it into a prototype function? Do you actually do this in your projects? Do you have a huge library of prototype additions that you include in every project? –  nurettin 1 hour ago
add comment

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

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

list.clear();
share|improve this answer
1  
@naomik Can you explain your reasoning why doing such a thing is frowned upon? –  Sam Sep 16 at 16:24
add comment

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);

share|improve this answer
19  
Why is this more cross-browser friendly? What browsers have issues with A.length? –  stricjux Nov 21 '11 at 15:12
1  
This is the most correct answer since this actually "clears the array content and retains the reference to the original array object. –  Shamasis Bhattacharya May 23 '12 at 8:32
3  
@jm2 what you are saying is not entirely true. It actually modifies the array in question and subsequently all references get affected. See the test on my jsFiddle: jsfiddle.net/shamasis/dG4PH –  Shamasis Bhattacharya Sep 26 '12 at 12:38
2  
@alex no it does not, splice modifies the array and returns the deleted entries. Read the docs first: developer.mozilla.org/en-US/docs/JavaScript/Reference/… –  David Oct 29 '12 at 16:22
1  
We could prevent the resulting array from being returned by using the comma operator: A.splice(0, A.length),0;. This would leave a return value of 0 just as A.length = 0; would. The resulting array is still created and should cause the script to run slower: (jsperf ~56% slower). Browser implementation will affect this although I see no reason why splice would be faster than setting length. –  Evan Kennedy Aug 18 at 3:47
show 3 more comments

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

A.length = 0;
share|improve this answer
4  
@Acorn Yes, it will work in all browsers. –  Matthew Crumley May 10 '11 at 22:01
7  
what does ECMAScript 5 Standard says about this? –  Pacerier Jun 21 '11 at 7:00
82  
@Pacerier: It still works in ES5. From section 15.4: "...whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted" –  Matthew Crumley Jun 21 '11 at 7:43
1  
@SteveSiebert It shouldn't in a correctly-implemented interpreter, and I don't know of any implementations that do. OF course, it's possible but it's not any more likely than other incorrect sources of leaks. –  Matthew Crumley Feb 8 '12 at 20:28
3  
@LosManos Even in strict mode, length is a special property, but not read only, so it will still work. –  Matthew Crumley Jan 4 at 14:18
show 19 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.