For deletion of elements in an array, two approaches can be used. They have their own merits regarding the way they perform the deletion.
Using delete array[index]:
This method deletes the element at the index specified, but does not modify the array. This means that at the place of the deleted index, the element is left undefined or null. This may cause problems when iterating through the array as the deleted index does not hold any value. The length of the array in this case remains the same.
Using the splice method:
The array.splice() method is used to add or remove items from an array. This method takes in 3 parameters, the index where the element’s id is to be inserted or removed, the number of items to be deleted and the new items which are to be inserted.
This method actually deletes the element at index and shifts the remaining elements leaving no empty index. This is useful as the array left after deletion can be iterated normally and displayed properly. The length of the array decreases using this method.
array.splice(index, items_to_remove, item1 ... itemX)
- Before clicking the button:
- After clicking the button:
- How to delete an array element based on key in PHP?
- PHP | Program to delete an element from array using unset() function
- How to delete last element from a map in C++
- PHP | MySQL Delete Query
- Node | URLSearchParams.delete()
- MongoDB | Delete Database using MongoShell
- How to recursively delete a directory and its entire contents (files + sub dirs) in PHP?
- p5.js | splice() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.