-1

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?

cweiske
  • 27,869
  • 13
  • 115
  • 180
Jake McAllister
  • 1,088
  • 3
  • 10
  • 24
  • How do you know you have to remove 213, not, 32 or 42? Does it come as an input from some source? – RaviH Feb 15 '14 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 Feb 15 '14 at 13:01

6 Answers6

5

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);
}
Sachin
  • 37,535
  • 7
  • 82
  • 97
1

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);
}
Suman Bogati
  • 5,931
  • 1
  • 18
  • 33
0

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

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0
a.splice(a.indexOf(213),1)

or

var i = a.indexOf(213)
a = a.slice(i,i+1,1)
markcial
  • 8,243
  • 4
  • 27
  • 40
0

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);
}
YorkshireKev
  • 229
  • 2
  • 8
-1

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.

dieortin
  • 458
  • 5
  • 15