пятница, 17 февраля 2012 г.

Javascript/jQuery. Remove item from array

jQuery have a very useful function grep. It can help you delete from array any element by some condition. It also can be used with objects.

Code example:

  1. arr = [1, 2, 3, 4, 5] // array inicial
  2. var removeItem = 2;   // item do array que deverá ser removido
  3. arr = jQuery.grep(arr, function(value) {
  4.         return value != removeItem;
  5.       });
  6. // new array
  7. // [1, 3, 4, 5]

If you don't use jQuery, you can try use next method:

  1. function removeByElement(arrayName,arrayElement)
  2.  {
  3.     for(var i=0; i<arrayName.length;i++ )
  4.      {
  5.         if(arrayName[i]==arrayElement)
  6.             arrayName.splice(i,1);
  7.       }
  8.   }

Enjoy!