Remove item from array in jQuery/javascript

By | 7 March, 2014

Extremely simple problem with a million solutions. These are just a couple of ways to do it. Go learn after the jump.

Shorthand version, this code removes only one (the first) occurence of the item in the array. This can be handy if you are sure there’s only one occurrence of the item in the array and want a simple solution.


var originalArray = [1,2,3,6,3,5];
var removeItem = 3;

originalArray.splice($.inArray(removeItem, originalArray), 1)

// the resulting array will be: [1,2,6,3,5]
// notice that only the first "3" is missing, as intended

This next piece of code removes all the occurrences of the item to be removed from the array:


var pcs = [1,2,3,6,3,5];
var removeItem = 3;

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

// the resulting array will be: [1,2,6,5]
// notice that all the "3"s are missing, as intended

Easy, eh? But like i said, this can be done in many different ways.

Here are some links to learn more:

jQuery.inArray()
.splice
jQuery.grep()