e.g.
a = [12, 213, 321, 312, 32, 42]
and i want to remove 213 from it
but i don’t ever know what order it will be in, in the array
How can I select it from the array and then also remove it?
-
How do you know you have to remove 213, not, 32 or 42? Does it come as an input from some source?RaviH– RaviH2014年02月15日 12:58:25 +00:00Commented Feb 15, 2014 at 12:58
-
basically what i am doing is inserting these numbers into array a. And i know what in there and i know which one i need to remove. All I want to know is how i can select and remove 213. But not by selecting it like a[1]Jake McAllister– Jake McAllister2014年02月15日 13:01:06 +00:00Commented Feb 15, 2014 at 13:01
6 Answers 6
Try this
array.splice(array.indexOf(213), 1);
Or if there is a possibility of having number which is not present in the array then you check it like this
var index = array.indexOf(213)
if(index > -1){
array.splice(index, 1);
}
2 Comments
You can use indexOf method to get index of element and can use splice() to remove that found element. eg:-
var array = a = [12, 213, 321, 312, 32, 42];
var index = array.indexOf(213);
//now remove this with splice method
if (index > -1) {
array.splice(index, 1);
}
Comments
You can use .splice() to remove the element, and use $.inArray() or Array.indexOf() to find the index of the element in the array
a = [12, 213, 321, 312, 32, 42]
a.splice($.inArray(a, 213), 1)
Note: Array.indexOf() was not used because of IE compatibility
Comments
a.splice(a.indexOf(213),1)
or
var i = a.indexOf(213)
a = a.slice(i,i+1,1)
Comments
You can find the index of the value with indexOf, then splice the array to remove the index.
Something like:
var idx = a.indexOf(213);
if (idx > -1) {
a.splice(idx, 1);
}
1 Comment
I think there are two ways to accomplish that:
The easier way is simply iterating over the array and pushing all the values in it except the one you want to delete to another array. Then you could redefine the previous array variable as the new array.
Another way could be to use the splice method, but I'm not familiar with it.