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?
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?
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 !==
.
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);
You didn't mention whether its required to retain the indices of the remaining elements in your array or not. On the basis that you can deal with having undefined members of an array, you can do:
var array = ["google","chrome","os","windows","os"];
delete array[1];
array[1] will then be undefined.
You may want to remove all of the items that match your string, or maybe remove items that pass or fail some test expression. Array.prototype.filter, or a substitute, is quick and versatile:
var array= ["google","chrome","os","windows","os"],
b= array.filter(function(itm){
return 'os'!= itm
});
alert(b)