Home How do I empty an array in JavaScript?

# How do I empty an array in JavaScript?

amir
1#
amir Published in 2009-08-05 09:08:39Z
 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?
Community
2#
 Ways to clear an existing array A: Method 1 (this was my original answer to the question) A = [];  This code 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. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A. This is also the fastest solution. This code sample shows the issue you can encounter when 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 2 (as suggested by Matthew Crumley) A.length = 0  This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property. Method 3 (as suggested by Anthony) A.splice(0,A.length)  Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever. Method 4 (as suggested by tanguy_k) while(A.length > 0) { A.pop(); }  This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer. Performance Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark. As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty. The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array). This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.
alex
3#
 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; 
JP Richardson
4#
JP Richardson Reply to 2012-02-26 22:28:36Z
 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);
leech
5#
 You can add this to your JavaScript file to allow your arrays to be "cleared": Array.prototype.clear = function() { this.splice(0, this.length); };  Then you can use it like this: var list = [1, 2, 3]; list.clear();  Or if you want to be sure you don't destroy something: if (!Array.prototype.clear) { Array.prototype.clear = function() { this.splice(0, this.length); }; }  Lots of people think you shouldn't modify native objects (like Array), and I'm inclined to agree. Please use caution in deciding how to handle this.
6#
 Array.prototype.clear = function() { this.length = 0; };  And call it: array.clear();
tanguy_k
7#
 Here the fastest working implementation while keeping the same array: Array.prototype.clear = function() { while (this.length) { this.pop(); } };  FYI Map defines clear() so it would seem logical to have clear() for Array too. Or as an Underscore.js mixin: _.mixin({ clearArray: function(array) { while (array.length) { array.pop(); } } });  Or a simple function: function clearArray(array) { while (array.length) { array.pop(); } }  FYI it cannot be simplified to while (array.pop()): the tests will fail. And the tests 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); // Even with undefined or null inside array = [1, undefined, 3, null, 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 http://jsperf.com/array-destroy/152
Community
8#
 Use a modified version of Jan's initial suggestion: var originalLength = A.length; for (var i = originalLength; i > 0; i--) { A.pop(); } 
matanster
9#
 In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in @tanguy_k's answer above. (for an intro to the aforementioned tab you can check out here) Stackoverflow forces me to copy the jsfiddle so here it is:  Quantifier:
 And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.
Louis
10#
 A.splice(0); I just did this on some code I am working on. It cleared the array.
Peter Mortensen
11#
Peter Mortensen Reply to 2015-11-11 19:41:42Z
 Performance test: http://jsperf.com/array-clear-methods/3 a = []; // 37% slower a.length = 0; // 89% slower a.splice(0, a.length) // 97% slower while (a.length > 0) { a.pop(); } // Fastest 
Laxmikant Dange
12#
Laxmikant Dange Reply to 2018-01-18 11:36:29Z
 If you are using a = [];  Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory. For ex. var a=[1,2,3]; var b=a; a=[]; console.log(b);// It will print [1,2,3];  or a.length = 0;  When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector. Instead of these two solutions are better. a.splice(0,a.length)  and while(a.length > 0) { a.pop(); }  As per previous answer by kenshou.html, second method is faster.
13#
 There is a lot of confusion and misinformation regarding the while;pop/shift performance both in answers and comments. The while/pop solution has (as expected) the worst performance. What's actually happening is that setup runs only once for each sample that runs the snippet in a loop. eg: var arr = []; for (var i = 0; i < 100; i++) { arr.push(Math.random()); } for (var j = 0; j < 1000; j++) { while (arr.length > 0) { arr.pop(); // this executes 100 times, not 100000 } }  I have created a new test that works correctly : http://jsperf.com/empty-javascript-array-redux Warning: even in this version of the test you can't actually see the real difference because cloning the array takes up most of the test time. It still shows that splice is the fastest way to clear the array (not taking [] into consideration because while it is the fastest it's not actually clearing the existing array).
MultiplyByZer0
14#
 The answers that have no less that 2739 upvotes by now are misleading and incorrect. The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4]. Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false. This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own. Let's say your mother asks you to empty the trash can. You don't bring in a new one as if you've done what you've been asked for. Instead, you empty the trash can. You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in A = [1,2,3,4]; A = []; Emptying an array object is the easiest thing ever: A.length = 0;  This way, the can under "A" is not only empty, but also as clean as new! Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in: while(A.length > 0) { A.pop(); }  Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in: A.splice(0, A.length);  No, you were asked to empty it: A.length = 0;  This is the only code that correctly empties the contents of a given JavaScript array.
Yash
15#
 To Empty a Current memory location of an array use: 'myArray.length = 0' or 'myArray.pop() UN-till its length is 0' length : You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases. pop() : The pop method removes the last element from an array and returns that returns the removed value. shift() : The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. Example: var arr = ['77']; arr.length = 20; console.log("Increasing : ", arr); // (20) ["77", empty × 19] arr.length = 12; console.log("Truncating : ", arr); // (12) ["77", empty × 11] var mainArr = new Array(); mainArr = ['1', '2', '3', '4']; var refArr = mainArr; console.log('Current', mainArr, 'Refered', refArr); refArr.length = 3; console.log('Length: ~ Current', mainArr, 'Refered', refArr); mainArr.push('0'); console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr); mainArr.poptill_length(0); console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr); Array.prototype.poptill_length = function (e) { while (this.length) { if( this.length == e ) break; console.log('removed last element:', this.pop()); } };  new Array() | [] Create an Array with new memory location by using Array constructor or array literal. mainArr = []; // a new empty array is addressed to mainArr. var arr = new Array('10'); // Array constructor arr.unshift('1'); // add to the front arr.push('15'); // add to the end console.log("After Adding : ", arr); // ["1", "10", "15"] arr.pop(); // remove from the end arr.shift(); // remove from the front console.log("After Removing : ", arr); // ["10"] var arrLit = ['14', '17']; console.log("array literal « ", indexedItem( arrLit ) ); // {0,14}{1,17} function indexedItem( arr ) { var indexedStr = ""; arr.forEach(function(item, index, array) { indexedStr += "{"+index+","+item+"}"; console.log(item, index); }); return indexedStr; }  slice() : By using slice function we get an shallow copy of elements from the original array, with new memory address, So that any modification on cloneArr will not affect to an actual|original array. var shallowCopy = mainArr.slice(); // this is how to make a copy var cloneArr = mainArr.slice(0, 3); console.log('Main', mainArr, '\tCloned', cloneArr); cloneArr.length = 0; // Clears current memory location of an array. console.log('Main', mainArr, '\tCloned', cloneArr); 
Damjan Pavlica
16#
Damjan Pavlica Reply to 2017-02-23 00:39:28Z
 If you use constants then you have no choice: const numbers = [1, 2, 3]  You can not reasign: numbers = []  You can only truncate: numbers.length = 0 
Cauterite
17#
 I'm surprised no one has suggested this yet: let xs = [1,2,3,4]; for (let i in xs) delete xs[i];  This yields an array in quite a different state from the other solutions. In a sense, the array has been 'emptied': xs => Array [ <4 empty slots> ] [...xs] => Array [ undefined, undefined, undefined, undefined ] xs.length => 4 xs[0] => ReferenceError: reference to undefined property xs[0]  You can produce an equivalent array with [,,,,] or Array(4)
 Use below if you need to empty Angular 2+ FormArray. public emptyFormArray(formArray:FormArray) { for (let i = formArray.controls.length - 1; i >= 0; i--) { formArray.removeAt(i); } } 
 You can easily create a function to do that for you, change the length or even add it to native Array as remove() function for reuse. Imagine you have this array: var arr = [1, 2, 3, 4, 5]; //the array  OK, just simply run this: arr.length = 0; //change the length  and the result is: [] //result  easy way to empty an array... Also using loop which is not necessary but just another way to do that: /* could be arr.pop() or arr.splice(0) don't need to return as main array get changed */ function remove(arr) { while(arr.length) { arr.shift(); } }  There are also tricky way which you can think about, for example something like this: arr.splice(0, arr.length); //[]  So if arr has 5 items, it will splice 5 items from 0, which means nothing will remain in the array. Also other ways like simply reassign the array for example: arr = []; //[]  If you look at the Array functions, there are many other ways to do this, but the most recommended one could be changing the length. As I said in the first place, you can also prototype remove() as it's the answer to your question. you can simply choose one of the methods above and prototype it to Array object in JavaScript, something like: Array.prototype.remove = Array.prototype.remove || function() { this.splice(0, this.length); };  and you can simply call it like this to empty any array in your javascript application: arr.remove(); //[]