tags:

views:

50

answers:

4

add and remove array value in jquery?

I have array of data var y = [1, 2, 3];

I want to remove 2 from array y.

Any one have idea how to remove particular value from array using jquery? I have tried pop() but its working like stack.

A: 

You can do something like this:

var y = [1, 2, 3]
var removeItem = 2;

y = jQuery.grep(y, function(value)) {
  return value != removeItem;
});

Result:

[1, 3]
Sarfraz
Thanks Sarfraz same answer I got from http://snipplr.com/view/14381/remove-item-from-array-with-jquery/It working now! Thank you.
Elankeeran
That is good news and yes the right modification was needed :)
Sarfraz
+1  A: 

by using simple javascript you can use this:

Array.remove('Valuetoberemoved'); 
ex: y.remove('2');

or this:

http://ejohn.org/blog/javascript-array-remove/

Vaibhav Gupta
+1 for the link...great read!
elo80ka
javascript Array doesn't have a `.remove()` method. You would need to prototype it as in the link you provided.
patrick dw
A: 

There is no native way to do this in Javscript. You could use a library or write a small function to do this instead: http://ejohn.org/blog/javascript-array-remove/

+1  A: 

With jQuery, you can do a single-line operation like this:

Example: http://jsfiddle.net/HWKQY/

y.splice( $.inArray(removeItem, y), 1 );

Uses the native .splice() and jQuery's $.inArray().

patrick dw
Thank you Patrick
Elankeeran
@Elankeeran - You're welcome. :o) I should note that this will remove only the first instance. If there are multiple to be removed, it wouldn't work.
patrick dw