How to remove specific value from array using jQuery

JqueryArrays

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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/

Solution 2 - Jquery

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().

Solution 3 - Jquery

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/

Solution 4 - Jquery

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')

Solution 5 - Jquery

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.

Solution 6 - Jquery

Remove Item in Array

var arr = ["jQuery", "JavaScript", "HTML", "Ajax", "Css"];
var itemtoRemove = "HTML";
arr.splice($.inArray(itemtoRemove, arr), 1);

Solution 7 - Jquery

//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')

Solution 8 - Jquery

> 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);
            }

Solution 9 - Jquery

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/

Solution 10 - Jquery

You can use .not function like this:

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

var newArr = $(arr).not([searchValue]).get();

Solution 11 - Jquery

//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;

Solution 12 - 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

Solution 13 - Jquery

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.

Solution 14 - Jquery

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.

Solution 15 - Jquery

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 });

Solution 16 - Jquery

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.

Solution 17 - Jquery

/** 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!

Solution 18 - Jquery

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

Solution 19 - Jquery

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

Solution 20 - Jquery

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElankeeranView Question on Stackoverflow
Solution 1 - JquerySarfrazView Answer on Stackoverflow
Solution 2 - Jqueryuser113716View Answer on Stackoverflow
Solution 3 - JqueryddagsanView Answer on Stackoverflow
Solution 4 - JqueryAamir AfridiView Answer on Stackoverflow
Solution 5 - JqueryvatsalView Answer on Stackoverflow
Solution 6 - Jquerypraveen dView Answer on Stackoverflow
Solution 7 - JqueryyesnikView Answer on Stackoverflow
Solution 8 - JqueryLuqman CheemaView Answer on Stackoverflow
Solution 9 - JqueryAussieNickView Answer on Stackoverflow
Solution 10 - JqueryVahid KhView Answer on Stackoverflow
Solution 11 - JqueryMarijan VukcevichView Answer on Stackoverflow
Solution 12 - JqueryandrewbView Answer on Stackoverflow
Solution 13 - Jqueryuser253780View Answer on Stackoverflow
Solution 14 - JqueryMahibView Answer on Stackoverflow
Solution 15 - JqueryBogdan LitescuView Answer on Stackoverflow
Solution 16 - JqueryStarkersView Answer on Stackoverflow
Solution 17 - JqueryKareemView Answer on Stackoverflow
Solution 18 - Jquerybaptiste baumeView Answer on Stackoverflow
Solution 19 - JquerythdoanView Answer on Stackoverflow
Solution 20 - JqueryBimView Answer on Stackoverflow