I have an array that looks like this: var y = [1, 2, 3];
I would like to remove 2
from array y
.
How can I remove a particular value from an array using jQuery? I have tried pop()
but that always removes the last element.
The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.
The grep() method in jQuery finds the array elements that satisfy the given filter function. It does not affect the original array. This method returns the filtered array, i.e., the elements that satisfy the given filter function.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects. If you are using jQuery you can use either the $. each() method or a for loop to iterate through an array.
A working JSFIDDLE
You can do something like this:
var y = [1, 2, 2, 3, 2] var removeItem = 2; y = jQuery.grep(y, function(value) { return value != removeItem; });
Result:
[1, 3]
http://snipplr.com/view/14381/remove-item-from-array-with-jquery/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With