-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?

2
  • How do you know you have to remove 213, not, 32 or 42? Does it come as an input from some source? Commented 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] Commented Feb 15, 2014 at 13:01

6 Answers 6

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

What happens when the given array have same values ? and some wants to delete that.Is this code will work for all the possible values.
@Bharatsoni it will delete the first one which find in the sequence.
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);
}

Comments

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

Comments

0
a.splice(a.indexOf(213),1)

or

var i = a.indexOf(213)
a = a.slice(i,i+1,1)

Comments

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);
}

1 Comment

Whoh, can't believe all these answers came in in the time it took to write mine! Now you have choices ;)
-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.