
1. Using the pop method
Array.pop will delete the last element of an array.
var array = [1,2,3,4,5];
array.pop();
array; // [1,2,3,4]
array.pop();
array; // [1,2,3]
2. Using the shift method
Array.shift will delete the first element of an array.
var array = [1,2,3,4,5];
array.shift();
array; // [2,3,4,5]
array.shift();
array; // [3,4,5]
3. Using the delete operator
The delete operator only erases the value of the element and makes the element as undefined. The length of the array stays unaffected.
var array = [1,2,3,4,5];
delete array[0];
delete array[2];
array.length ; // 5
4. Using the splice method
If we want to delete an element and change the length of the array, then we can use splice method. This method will remove n number of elements from the specific index.
MDN: The
splice()method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place (In the original array).
array.splice(index , deleteCount, item1, item2, ...)
-
index→ index from which the slice operation should start. -
deleteCount→ number of elements to be deleted from the index. -
item→ elements to be inserted
var array =[1,2,3,4,5];
array.splice(2,1);
array; //[1,2,4,5]
array.splice(0,1)
array; // [2,4,5]
5. Using the filter method
We can also use the filter method on an Array to remove an element in specific index of the array. But when we use filter, it creates a new array.
var array = [1,2,3,4,5];
var indexToDelete = 1;
let newArray = array.filter( (item, index) => {
if(index !== indexToDelete){
return item;
}
});
newArray; // [1,3,4,5]
6. Resetting an array
If we want to delete all elements of the array, then we can simply do it like this:
var array = [1,2,3,4,5]
array.length = 0;
or
array = [];
Thanks for Reading 📖. I hope you enjoyed the article. If you found any typos or mistakes, send me a private note 📝 Thanks 🙏 😊 .
Follow me JavaScript Jeep🚙💨 .
Please make a donation here. 98% of your donation is donated to someone needs food 🥘. Thanks in advance.
https://levelup.gitconnected.com/detecting-online-offline-in-javascript-1963c4fb81e1
https://levelup.gitconnected.com/detecting-online-offline-in-javascript-1963c4fb81e1