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

If there is an array, is it possible to empty with .remove()?

For instance,

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

How can I empty that?

share|improve this question
52  
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. – NagaJolokia Jul 7 at 2:19
add comment (requires an account with 50 reputation)

9 Answers

up vote 199 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
332  
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
13  
34 upvotes and 17 downvotes. Doesn't that deserve a special badge? :-) – Philippe Leybaert Jan 17 '12 at 15:50
4  
arr = new Array() is exactly the same as arr = [] – Philippe Leybaert May 16 '12 at 12:32
14  
-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
show 5 more commentsadd comment (requires an account with 50 reputation)

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
3  
what does ECMAScript 5 Standard says about this? – Pacerier Jun 21 '11 at 7:00
61  
@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
1  
@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 11 more commentsadd comment (requires an account with 50 reputation)

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
15  
Why is this more cross-browser friendly? What browsers have issues with A.length? – stricjux Nov 21 '11 at 15:12
Like @alex said, splice returns a new array. Not something you would want to do in a REPL. You could always void the expression but that's not an elegant solution. – Aadit M Shah Mar 15 '12 at 14:32
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
2  
@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
show 2 more commentsadd comment (requires an account with 50 reputation)

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
2  
Please don't encourage modification of the native objects. – naomik Jul 7 at 6:52
add comment (requires an account with 50 reputation)

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
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
Please don't encourage modification of the native objects. – naomik Jul 7 at 6:53
add comment (requires an account with 50 reputation)

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
6  
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 (requires an account with 50 reputation)
Array.prototype.clear = function()
{
    this.length = 0;
};

and call it: array.clear();

=)

share|improve this answer
Please don't encourage modification of the native objects. – naomik Jul 7 at 6:53
add comment (requires an account with 50 reputation)

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
add comment (requires an account with 50 reputation)

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
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
Please don't encourage modification of the native objects. – naomik Jul 7 at 6:54
add comment (requires an account with 50 reputation)

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.