How to Unset an Element in an Array in JavaScript
In this article, I’ll discuss the various methods of unsetting an element in an array in JavaScript.
-
Unset with the delete operator. #
The delete operator is the most straight-forward way to unset an element in an array in JavaScript. To unset an element, simply pass in the index of the element you want to unset.
<script> const myArray = [ {name:"Dipak", age:20}, {name:"Santosh", age:30}, {name:"Kajal", age:40} ]; delete myArray[1]; console.log(myArray) </script>
Output :
[ {name:"Dipak", age:20}, {name:"Kajal", age:40} ];
-
Unset with the splice() method. #
The splice() method is a more powerful way to unset an element in an array. It allows you to delete a range of elements from the array, and also insert new elements in the same place. To unset an element, you simply pass in the index of the element you want to delete and the number of elements you want to delete.
<script> const myArray = [ {name:"Dipak", age:20}, {name:"Santosh", age:30}, {name:"Kajal", age:40} ]; myArray.splice(1,1); console.log(myArray) </script>
Output :
[ {name:"Dipak", age:20}, {name:"Kajal", age:40} ];
-
Unset with the filter() method. #
The filter() method creates a new array with all elements that pass the test implemented by the provided function. It allows you to filter out any element you want to remove from the array. To unset an element, you simply pass in a function that returns false when the element you want to remove is encountered.<script> const myArray = [ {name:"Dipak", age:20}, {name:"Santosh", age:30}, {name:"Kajal", age:40} ]; let newArray = myArray.filter( item => item.name != 'Santosh') console.log(newArray) </script>
Output :
[ {name:"Dipak", age:20}, {name:"Kajal", age:40} ];
Conclusion #
There are several different ways to unset an element in an array in JavaScript. The most straight-forward way is to use the delete operator, which simply removes the element without affecting the order of the array. The splice() method is more powerful, allowing you to delete a range of elements and insert new elements in the same place. And the filter() method is the most versatile, allowing you to filter out any element you want to remove from the array. Depending on your specific situation, any of these methods can be used to unset an element in an array in JavaScript.