Javascript empty an existing array
A couple methods on how to empty an array in Javascript
Consider var my_array = [1, 2, 3]; and var other_array = my_array;
-
New empty array references remain unchanged
Be aware that if you had any references to my_array they’ll remain unchanged as you would be pointing my_array to a newly created one.
my_array = []; // other_array is still [1, 2, 3]
-
Setting array.length to 0
Be aware that as we’re updating the value, all references to my_array will still point to the same changed array.
my_array.length = 0; // other_array is now empty []
-
Array splice() method
Be aware that as we’re updating the value, all references to my_array will still point to the same changed array.
my_array.splice(0, my_array.length);
// other_array is now empty [] -
Lodash’s remove() method
Be aware that as we’re updating the value, all references to my_array will still point to the same changed array.
_.remove(my_array, undefined);
// other_array is now empty []