JavaScript: How to delete an element by Value in an array?
Delete an element from an array using existing methods in JavaScript
In JavaScript, to delete an item from an array, we have the following methods:
1) pop()
Removes an element from the end of the JavaScript array.
2) shift()
Removes an element from the beginning of the JavaScript array.
3) splice()
Removes an element at the specified index of the JavaScript array.
4) delete operator (Ex: delete arr[3])
deletes an element at the specified index of the JavaScript array. But, null will be inserted at that index as it won’t change the length of the array.
What options do we have to remove an element by its value and resize the array automatically?
a) Use the splice and indexOf functions
let arr = [‘One’, ‘Two’, ‘Three’, ‘Four’]
Remove an element with value ‘Three’.
arr.splice(arr.indexOf(‘Three’), 1);
console.log(arr);
b) Use filter function
let arr = [‘One’, ‘Two’, ‘Three’, ‘Four’]
Remove an element with value ‘Three’.
let filteredArr = arr.filter(function(value, index, arr){ return value !==’Three’;});
Note that the above filter function returns a new array.
Thank you for reading! Please 👏and follow me if you liked this post, as it encourages me to write more!