9

I'm trying to figure out how to remove item from serializedArray by using the index. The following scenario:

[ 
    { 'name' : 'item1', 'value' : '1' }, 
    { 'name' : 'item2', 'value' : '2' }, 
    { 'name' : 'item3', 'value' : 3 } 
]

Now I would like to remove 'item2' - I can use the following function - but not sure how to remove it - is there some sort of unset() method or something like this:?

serializeRemove : function(thisArray, thisName) {
    "use strict";
    $.each(thisArray, function(index, item) {
        if (item.name == thisName) {
            // what to do here ?        
        }
    });
}
Spencer Mark
  • 5,073
  • 8
  • 25
  • 55
  • Where does this serialzed array come from? could you exclude it from the collection that creates this serialized array? – Kevin B Dec 03 '12 at 16:49

2 Answers2

4

You could use vanilla JS' filter() method like this:

serializeRemove : function(thisArray, thisName) {
    "use strict";
    return thisArray.filter( function( item ) {
               return item.name != thisName;
           });
}

filter() uses the callback function to test each element of the array. If the function returns true the element will be in the result. If it returns false, the element will be dropped.

filter() is supported by all major browsers and IE9+.

Sirko
  • 65,767
  • 19
  • 135
  • 167
3

You can use delete which is a standard JavaScript operator: http://jsfiddle.net/2NsUD/

var array = [ 
    { 'name' : 'item1', 'value' : '1' }, 
    { 'name' : 'item2', 'value' : '2' }, 
    { 'name' : 'item3', 'value' : 3 } 
];

var arrayClean = function(thisArray, thisName) {
    "use strict";
    $.each(thisArray, function(index, item) {
        if (item.name == thisName) {
            delete thisArray[index];      
        }
    });
}

console.log(array);
arrayClean(array, 'item3');
console.log(array);​
Cymen
  • 12,733
  • 4
  • 47
  • 68
  • 2
    Keep in mind that the length of array remains unaffected -- which may not be desired. – Salman A Dec 03 '12 at 16:45
  • 2
    Good point -- there are other options that will decrease the length: http://stackoverflow.com/questions/500606/javascript-array-delete-elements – Cymen Dec 03 '12 at 16:48
  • 1
    "delete array[index];" should be "delete thisArray[index]; " to make this work – fudu May 14 '19 at 06:49