In this blog, we are going to learn the easy way of deleting array elements and 3 positions which are (i) at the start (ii) at the end and (iii) in the middle. So without further ado let’s start the article with live examples.
Deleting the last element
Deleting an element from the last is very easy we just need to call the pop() method.
The pop() method removes the last element of an array and returns that element.
Deleting the 1st element
The shift() method does the work for us, it removes the first element from an array and returns that removed element.
Deleting element from the middle
There are various methods to which can help us to delete elements from the middle
1. Using the Splice method (known index)
The splice() method adds/removes items to/from an array, and returns the removed item(s). The syntax for deleting elements is as follows:
– index: The index at which to start deleting the array elements.
– count: An integer indicating the number of elements in the array to be removed.
2. Using the Slice method (known index)
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
– start: Optional. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array. If omitted, it acts like “0”
– end: Optional. An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array
Using the slice() method and spread operator for deleting
const firstArr = items.slice(0, index); const secondArr = items.slice(index + 1); newArray = [...firstArr , ...secondArr]
Using the slice() method and concat() method for deleting
const firstArr = items.slice(0, index); const secondArr = items.slice(index + 1); newArray = firstArr.concat(secondArr);
3. Using the filter method (only value known)
The above 2 methods help us in deleting the elements when we know the index but in the case where we only know the value to be deleted then we use filter() method.
The filter() method creates a new array with all elements that pass the condition.