432

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.

Cœur
  • 32,421
  • 21
  • 173
  • 232
Elankeeran
  • 5,944
  • 7
  • 35
  • 56
  • 8
    **WARNING**: some of the most upvoted answers might have side effects, e.g., doing wrong operations when the array doesn't contain the element to be removed. *Please use them with care*. – Ricardo Oct 30 '15 at 17:13
  • This answer worked for me, with plain javascript: http://stackoverflow.com/a/5767357/4681687 – chimos Oct 05 '16 at 12:14
  • see my comment under the use of splice() and $.inArray(), I have solved this issue WITHOUT the use of a loop, and it is clean. – user253780 Dec 09 '19 at 13:16

20 Answers20

637

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/

Rahul Gupta
  • 7,933
  • 5
  • 49
  • 60
Sarfraz
  • 355,543
  • 70
  • 511
  • 562
376

With jQuery, you can do a single-line operation like this:

Example: http://jsfiddle.net/HWKQY/

y.splice( $.inArray(removeItem, y), 1 );

Uses the native .splice() and jQuery's $.inArray().

user113716
  • 299,514
  • 60
  • 431
  • 433
  • 13
    @Elankeeran - You're welcome. :o) I should note that this will remove only the first instance. If there are multiple to be removed, it wouldn't work. – user113716 Aug 29 '10 at 19:38
  • 8
    I also changed the removeItem to a value that does NOT exist in the array and it removed the last item in the array. Use this if you're not certain of the removedItem's existence: y = $.grep(y, function (val) { return val != removeItem ; }); – Solburn Jul 26 '11 at 18:18
  • It's also good to note that if you know the index of the item you can remove it just using `.splice(1, 1)` where first expression is the index and the second is how many to delete at that index. So to remove 2 you would know that it is on index 1. `y.splice( 1 ,1 );` http://msdn.microsoft.com/en-us/library/wctc5k7s%28v=VS.94%29.aspx – Joshua Pack Nov 15 '12 at 20:58
  • 55
    WARNING - May remove wrong item! $.inArray returns -1 if the value is not present and .splice treats a negative index as 'from the end' so if the value you're trying to remove is not present, some other value will be removed instead. Also $.grep will remove all occurrences whereas this method will only remove the first. – Ryan Williams Jan 09 '14 at 05:46
  • This doesn't seem to work if the removeItem is the only value in the array. – scrowler Jun 04 '14 at 22:04
  • 2
    To remedy both issues described above, use a `while` loop and a temporary variable like this: `var found; while ((found = $.inArray(removeItem, y)) !== -1) y.splice(found, 1);` –  Oct 25 '14 at 23:47
  • 2
    Though it's much nicer with ES5 `.indexOf()` instead of jQuery because you can use the last index found as the starting point for the next search, which is far more efficient than searching the entire array every time. `var found=0; while ((found = y.indexOf(removeItem, found)) !== -1) y.splice(found, 1);` –  Oct 26 '14 at 00:00
  • NOTE - this function removes the elements and *returns* the deleted ones. So you should not use the return value, if that is not your intent. – cederlof Dec 15 '15 at 13:31
  • @user1106925 rather than creating an unnecessary loop within this construct (or forcing it to assume we will always find the intended removal item), we can simply parse the same function we were using in arg_1 in a boolean fashion. This way, if the item cannot be found, the number of elements to splice will be numerically 'false'. ` y.splice( $.inArray(removeItem,y) , $.inArray(removeItem,y) ); ` – user253780 Dec 09 '19 at 13:13
  • @user253780: That does not make sense. The `$.inArray()` command will return 0 when the index of the item found is 0 (first slot in the array), that item will never be removed. Secondly, when the index of the item found is larger than 1 (3rd item or higher) multiple items will be removed. – Guido Bouman Dec 16 '19 at 09:22
61

jQuery.filter method is useful. This is available for Array objects.

var arr = [1, 2, 3, 4, 5, 5];

var result = arr.filter(function(elem){
   return elem != 5; 
});//result -> [1,2,3,4]

http://jsfiddle.net/emrefatih47/ar0dhvhw/

In Ecmascript 6:

let values = [1,2,3,4,5];
let evens = values.filter(v => v % 2 == 0);
alert(evens);

https://jsfiddle.net/emrefatih47/nnn3c2fo/

ddagsan
  • 1,573
  • 15
  • 20
  • 4
    Seems to work the best out of the proposed solutions, even though it's actually not altering the existing array but rather creating a new one. It also works with non-existing values or an empty array. Quick performance check in JSFiddle I did: with an array with 800.000 values it took about 6 seconds to complete. Not sure if that's fast though. – Flo Jul 14 '16 at 20:35
  • 2
    This solution is using vanilla JS high order function filter, **NOT** jQuery filter method. – Kalimah Dec 14 '19 at 00:00
  • I love it! It seems the best solution even though it is not jquery... – Sam Jun 09 '20 at 08:50
35

You can use underscore.js. It really makes things simple.

In your case all the code that you will have to write is -

_.without([1,2,3], 2);

and the result will be [1,3].

It reduces the code that you write.

B. Fleming
  • 5,778
  • 1
  • 16
  • 29
vatsal
  • 3,387
  • 1
  • 17
  • 19
  • Imho `_.without(2, [1,2,3]);` would be a better design. Now it looks more like yodascore.js – mzrnsh Nov 06 '20 at 08:59
35

Not a jQuery way but... Why don't use simpler way. Remove 'c' from following array

var a = ['a','b','c','d']
a.splice(a.indexOf('c'),1);
>["c"]
a
["a", "b", "d"]

You can also use: (Note to myself: Don’t modify objects you don’t own)

Array.prototype.remove = function(v) { this.splice(this.indexOf(v) == -1 ? this.length : this.indexOf(v), 1); }
var a = ['a','b','c'];
a.remove('c'); //value of "a" is now ['a','b']

Adding is simplera.push('c')

Aamir Afridi
  • 6,095
  • 3
  • 38
  • 41
27

Remove Item in Array

var arr = ["jQuery", "JavaScript", "HTML", "Ajax", "Css"];
var itemtoRemove = "HTML";
arr.splice($.inArray(itemtoRemove, arr), 1);
tmthydvnprt
  • 8,832
  • 7
  • 49
  • 66
praveen d
  • 281
  • 4
  • 6
15
//This prototype function allows you to remove even array from array
Array.prototype.remove = function(x) { 
    var i;
    for(i in this){
        if(this[i].toString() == x.toString()){
            this.splice(i,1)
        }
    }
}

Example of using

var arr = [1,2,[1,1], 'abc'];
arr.remove([1,1]);
console.log(arr) //[1, 2, 'abc']

var arr = [1,2,[1,1], 'abc'];
arr.remove(1);
console.log(arr) //[2, [1,1], 'abc']

var arr = [1,2,[1,1], 'abc'];
arr.remove('abc');
console.log(arr) //[1, 2, [1,1]]

To use this prototype function you need to paste it in your code. Then you can apply it to any array with 'dot notation':

someArr.remove('elem1')
yesnik
  • 2,425
  • 23
  • 20
  • A bit more explanation wouldnt go a miss here! – Gaz Winter Dec 21 '12 at 10:44
  • To use this prototype function you need to paste it in your code. Then you can apply it to any array with 'dot notation', for example: someArr.remove('elem1') – yesnik Jan 28 '13 at 03:01
  • 3
    The only problem with something like this is it overwrites the global Array object's remove method, meaning any other code in the project that depends on the default behavior ends up with buggy behavior. – jmort253 Sep 24 '13 at 16:33
  • 2
    Another problem is that the global variable `i` gets overwritten. – Roland Illig May 23 '14 at 17:11
6

First checks if element exists in the array

$.inArray(id, releaseArray) > -1

above line returns the index of that element if it exists in the array, otherwise it returns -1

 releaseArray.splice($.inArray(id, releaseArray), 1);

now above line will remove this element from the array if found. To sum up the logic below is the required code to check and remove the element from array.

  if ($.inArray(id, releaseArray) > -1) {
                releaseArray.splice($.inArray(id, releaseArray), 1);
            }
            else {
                releaseArray.push(id);
            }
Luqman Cheema
  • 143
  • 2
  • 3
5

You can use .not function like this:

var arr = [ 1 , 2 , 3 , 5 , 8];
var searchValue = 2;

var newArr = $(arr).not([searchValue]).get();
Vahid Kh
  • 99
  • 2
  • 6
  • 2
    This will wipe out the whole array if the value isn't in there, so a searchValue = 4 will return a blank array. – Julian K Aug 09 '15 at 01:59
  • 4
    I have copied the code into jsfiddle, changed `searchValue` to 4, ran the code, no problem detected. All values were still present.@JulianK – RST Feb 18 '17 at 18:56
5

There is no native way to do this in Javascript. You could use a library or write a small function to do this instead: http://ejohn.org/blog/javascript-array-remove/

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
AussieNick
  • 83
  • 5
4

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
andrewb
  • 4,961
  • 6
  • 32
  • 51
4

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.

user253780
  • 76
  • 1
  • 7
4
//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;
3

There is a simple solution with splice. According to W3School splice syntax is following;

array.splice(index, howmany, item1, ....., itemX)

index Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array

howmany Required. The number of items to be removed. If set to 0, no items will be removed

item1, ..., itemX Optional. The new item(s) to be added to the array

Keep that in mind, the following js will pop one or more matched item from the given array if found, otherwise wouldn't remove the last item of the array.

var x = [1,2,3,4,5,4,4,6,7];
var item = 4;
var startItemIndex = $.inArray(item, x);
var itemsFound = x.filter(function(elem){
                            return elem == item;
                          }).length;

Or

var itemsFound = $.grep(x, function (elem) {
                              return elem == item;
                           }).length;

So the final should look like the following

x.splice( startItemIndex , itemsFound );

Hope this helps.

Mahib
  • 3,493
  • 5
  • 48
  • 57
2

I had a similar task where I needed to delete multiple objects at once based on a property of the objects in the array.

So after a few iterations I end up with:

list = $.grep(list, function (o) { return !o.IsDeleted });
Bogdan Litescu
  • 789
  • 7
  • 8
2

I'd extend the Array class with a pick_and_remove() function, like so:

var ArrayInstanceExtensions = {
    pick_and_remove: function(index){
        var picked_element = this[index];
        this.splice(index,1);
        return picked_element;
    } 
};
$.extend(Array.prototype, ArrayInstanceExtensions);

While it may seem a bit verbose, you can now call pick_and_remove() on any array you possibly want!

Usage:

array = [4,5,6]           //=> [4,5,6]
array.pick_and_remove(1); //=> 5
array;                    //=> [4,6]

You can see all of this in pokemon-themed action here.

Starkers
  • 9,083
  • 14
  • 82
  • 143
2
/** SUBTRACT ARRAYS **/

function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                difference.push(array1[i]);
        }
    }
return difference;
}  

You can then call the function anywhere in your code.

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty :P"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

Kareem
  • 4,110
  • 37
  • 34
2

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`},
1

To safely remove 2 from the array using vanilla JavaScript:

// Define polyfill for browsers that don't natively support Array.indexOf()
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var k;
    if (this===null) {
      throw new TypeError('"this" is null or not defined');
    }
    var O = Object(this),
      len = O.length >>> 0;
    if (len===0) return -1;
    var n = +fromIndex || 0;
    if (Math.abs(n)===Infinity) n = 0;
    if (n >= len) return -1;
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    while (k < len) {
      if (k in O && O[k]===searchElement) return k;
      ++k;
    }
    return -1;
  };
}

// Remove first instance of 2 from array
if (y.indexOf(2) > -1) {
  y.splice(y.indexOf(2), 1);
}

/* To remove all instances of 2 from array, change 'if' to 'while':
while (y.indexOf(2) > -1) {
  y.splice(y.indexOf(2), 1);
}
*/

console.log(y);  // Returns [1, 3]

Polyfill source: Mozilla

thdoan
  • 15,024
  • 1
  • 46
  • 40
1

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>
Bim
  • 51
  • 2