1

How to remove item from jquery array object.

I used splice method as follows. But it slice next item of array[i].

    $.each(array, function (i, item) {
    var user = array[i];
    jQuery.each(array2, function (index, idata) {
        debugger
        if (idata.Id == user.UserId) {
            tempFlag = 1;
            return false; // this stops the each
        }
        else {
            tempFlag = 0;
        }
    });

    if (tempFlag != 1) {
     //removes an item here

        array.splice(user, 1);
    }
})

Can anyone tell me where i am wrong here?

Kalaivani
  • 477
  • 3
  • 9
  • 17

2 Answers2

5

You should try this to remove element from array in jQuery:

jQuery.removeFromArray = function(value, arr) {
    return jQuery.grep(arr, function(elem, index) {
        return elem !== value;
    });
};

var a = [4, 8, 2, 3];

a = jQuery.removeFromArray(8, a);

Check this Link for more : Clean way to remove element from javascript array (with jQuery, coffeescript)

Community
  • 1
  • 1
Anand Soni
  • 5,070
  • 11
  • 50
  • 101
  • That is clean, but not applicable to the question in its current form, as the code is not just looking for items in an array, it's looking for items in an array where another array contains an item where one property corresponds to a property of the item. – Guffa Feb 20 '12 at 12:59
4

You are using the value in user as index, i.e. array[i], instead of the value i.

$.each(array, function (i, item) {
  var user = array[i];
  jQuery.each(array2, function (index, idata) {
    debugger
    if (idata.Id == user.UserId) {
      tempFlag = 1;
      return false; // this stops the each
    } else {
      tempFlag = 0;
    }
  });

  if (tempFlag != 1) {
    //removes an item here
    array.splice(i, 1);
  }
});

You may get problems from removing items from the array that you are currently looping, though...

Guffa
  • 687,336
  • 108
  • 737
  • 1,005