[jquery] How to remove specific value from array using jQuery

My version of user113716's answer. His removes a value if no match is found, which is not good.

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

var i = $.inArray(removeItem,y)

if (i >= 0){
    y.splice(i, 1);
}

alert(y);

This now removes 1 item if a match is found, 0 if no matches are found.

How it works:

  • $.inArray(value, array) is a jQuery function which finds the first index of a value in an array
  • The above returns -1 if the value is not found, so check that i is a valid index before we do the removal. Removing index -1 means removing the last, which isn't helpful here.
  • .splice(index, count) removes count number of values starting at index, so we just want a count of 1