How to use splice() Method In Javascript
This method is used for deleting the existing element or replacing the content of the array by removing/adding a new element.
Example: In this example, the splice method will be used to delete the item from an array.
Javascript
function myFunc() { let myFruit = [ "apple" , "banana" , "grapes" , "strawberry" ]; const removed = myFruit.splice(2, 2, "guava" ); // Removed element in the array console.log(removed); // Length of the original array after deleting console.log(myFruit.length); // Original array after deleting the array console.log(myFruit); } myFunc(); |
Output
[ 'grapes', 'strawberry' ] 3 [ 'apple', 'banana', 'guava' ]
Different ways to delete an item from an array using JavaScript
In Javascript, we do not have any array.remove() method for deleting the element. we will have an array and we need to delete a given item from that array and return the resulting array in the console.
These are the following methods for solving this problem:
Table of Content
- Using for loop and push() Method
- Using Pop() Method
- Using shift() Method
- Using splice() Method
- Using filter() Method
- Using delete Operator
- Using Lodash _.remove() Method
Note: There are some other methods that are created by JavaScript inbuilt methods.
Contact Us