Ways to empty an array in Javascript

Posted By Aastha Rawat | 31-Jan-2019

Ways of empty an array in Javascript?


JavaScript arrays are used to store multiple values in a single variable. It allows us to group values together and iterates over them. We can add and remove array elements in different ways. But yet, there is not a simple Array.remove method.

So, how do we delete or remove an element from a JavaScript array?

Instead of a delete or remove an element from a method, the JavaScript array provides many varieties of ways from which we can clean array values.

Method 1 – Use splice() method

The splice() can be used to add or remove elements from an array. The 1st argument specifies the location at which to begin adding or removing elements. The 2nd argument specifies the number of elements to remove. 

 e.g 1.
var array =[1,4,5,6];
array.splice(0,array.length)

e.g 2.
var array = [11, 12, 13, 14, 15, 16, 17, 18, 19];
var removedElements = array.splice(2,3);

/*
removed === [13, 14, 15]
array === [11, 12, 116, 7, 118, 9]
*/
 

In the above e.g (2) an array containing the removed elements is returned by the splice method. we can see the removed elements array contains [13, 14, 15] and the original array contains the remaining values.


Method II – Clear or Reset a JavaScript Array

e.g var array = [11, 12, 13, 14, 15];
array = [];
//a new, empty array!
 

In the above e.g it will set the variable array to a new empty array. 

 


Method III – Set length to zero

 var array = [1, 2, 3, 4, 5];
 console.log(array); // Output [1, 2, 3, 4, 5]
 array.length = 0;
 console.log(array); // Output []
 

This doesn't create a new array, but change the existing array by setting its length to 0. 

Method IV – Using pop() method

 var array = [1, 2, 3, 4, 5];
 console.log(array); // Output [1, 2, 3, 4, 5]
  while (array.length) {
    array.pop();
  }
 console.log(array); // Output []
 

There is another way, using a while loop.

 

Thanks,

Request for Proposal

Recaptcha is required.

Sending message..