How to remove specific value from array using jQuery

Viewed 782974

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.

20 Answers
//in case somebody needs something like this:  multidimensional array (two items)

var ar = [[0,'a'],[1,'b'],[2,'c'],[3,'d'],[4,'e'],[5,'f']];

var removeItem = 3;  


ar = jQuery.grep(ar, function(n) {
  return n[0] != removeItem;   //or n[1] for second item in two item array
});
ar;

The second most upvoted answer here is on the closest track possible to a one-liner jQuery method of the intended behavior the OP wants, but they stumbled at the end of their code, and it has a flaw. If your item to be removed isn't actually in the array, the last item will get removed.

A few have noticed this issue, and some have offered ways to loop through to guard against this. I offer the shortest, cleanest method I could find, and I have commented under their answer for the way to fix their code according to this method.

var x = [1, 2, "bye", 3, 4];
var y = [1, 2, 3, 4];
var removeItem = "bye";

// Removing an item that exists in array
x.splice( $.inArray(removeItem,x), $.inArray(removeItem,x) ); // This is the one-liner used

// Removing an item that DOESN'T exist in array
y.splice( $.inArray(removeItem,y), $.inArray(removeItem,y) ); // Same usage, different array

// OUTPUT -- both cases are expected to be [1,2,3,4]
alert(x + '\n' + y);

array x will remove the element "bye" easily, and array y will be untouched.

The use of the argument $.inArray(removeItem,array) as a second argument actually ends up being the length to splice. Since the item was not found, this evaluates to array.splice(-1,-1);, which will just result in nothing being spliced... all without having to write a loop for this.

Try this it works for me

_clientsSelected = ["10", "30", "12"];
function (removeItem) {
console.log(removeItem);
   _clientsSelected.splice($.inArray(removeItem, _clientsSelected), 1);
   console.log(_clientsSelected);
`enter code here`},

Just to add onto the answer from Sarfraz, suprised nobody made it into a function yet.

Use the answer from ddagsan using the .filter method if you have the same value more than once in your array.

function arrayRemoveVal(array, removeValue){
 var newArray = jQuery.grep(array, function(value) {return value != removeValue;});
 return newArray;
}
var promoItems = [1,2,3,4]; 
promoItems = arrayRemoveVal(promoItems, 3);// removes 3
console.log(promoItems);
promoItems = arrayRemoveVal(promoItems, 3);// removes nothing
console.log(promoItems);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

Related