I have an array
var array = ["google","chrome","os","windows","os"];
I want to delete the value "chrome"
from the array without the array becoming a string. Is there a way to do this?
Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.
You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.
Using ArrayList We can use an ArrayList to perform this operation. To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array.
To remove an element from an array by ID in JavaScript, use the findIndex() method to find the index of the object with the ID in the array. Then call the splice() method on the array, passing this index and 1 as arguments to remove the object from the array.
Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.
There's no faster way than finding it and then removing it. Finding it you can do with a loop or (in implementations that support it) indexOf
. Removing it you can do with splice
.
Live example: http://jsbin.com/anuta3/2
var array, index;
array = ["google","chrome","os","windows","os"];
if (array.indexOf) {
index = array.indexOf("chrome");
}
else {
for (index = array.length - 1; index >= 0; --index) {
if (array[index] === "chrome") {
break;
}
}
}
if (index >= 0) {
array.splice(index, 1);
}
This wraps it up into a convenient function:
function remove_element(array, item) {
for (var i = 0; i < array.length; ++i) {
if (array[i] === item) {
array.splice(i, 1);
return;
}
}
}
var array = ["google", "chrome", "os", "windows", "os"];
remove_element(array, "chrome");
or (for browsers that support indexOf
):
function remove_element(array, item) {
var index = array.indexOf(item);
if (-1 !== index) {
array.splice(index, 1);
}
}
Edit: Fixed up with ===
and !==
.
Use the splice method of the Array class.
array.splice(1, 1);
The splice() method adds and/or removes elements to/from an array, and returns the removed element(s).
array.splice(indexOfElement,noOfItemsToBeRemoved);
in your case
array.splice(1, 1);
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