Home » Jquery » How to remove specific value from array using jQuery

How to remove specific value from array using jQuery

Posted by: admin November 2, 2017 Leave a comment

Questions:

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.

Answers:

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/

Questions:
Answers:

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

Questions:
Answers:

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

In you case the code that you will have to right is –

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

and the result will be [1,3].

It reduces the code that you write.

Questions:
Answers:

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/

Questions:
Answers:

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

Questions:
Answers:
//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')

Questions:
Answers:

Remove Item in Array

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

Questions:
Answers:

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/

Questions:
Answers:

You can use .not function like this:

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

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

Questions:
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;

Questions:
Answers:

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

Questions:
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:
/** 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!

Questions:
Answers:

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
Questions:
Answers:

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