I have an array like this
arr = ["orange","red","black","white"]
I want to augment the array object defining a deleteElem()
method which acts like this:
arr2 = arr.deleteElem("red"); // ["orange","black","white"] (with no hole)
What is the best way to accomplish this task using just the value parameter (no index)?
We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.
Most efficient way to remove an element from an array, then reduce the size of the array.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
Here's how it's done:
var arr = ["orange","red","black","white"]; var index = arr.indexOf("red"); if (index >= 0) { arr.splice( index, 1 ); }
This code will remove 1 occurency of "red" in your Array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With