Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove specific value from array using jQuery

Tags:

arrays

jquery

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.

like image 572
Elankeeran Avatar asked Aug 29 '10 18:08

Elankeeran


People also ask

How do you check if a value exists in an array JS?

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.

What is grep in jQuery?

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.

How do I remove a specific element from an array?

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.

Can we use for loop in jQuery?

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.


1 Answers

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/

like image 192
Sarfraz Avatar answered Oct 10 '22 03:10

Sarfraz