Tom Tom - 3 months ago 10
Javascript Question

Jquery remove entry from array based on partial match

My array looks like this:
"MODE:ID:A:B"

["add:123456789:0:0", "del:99887766:0:0", "edit:1471872633890:8845:0", "add:4875125862:1523:NE"]


When a user deletes a row from a table a
del
entry is added to the array.

If the user has added a new entry to the table a
add
entry is added to the array.

If the user edits an entry an
edit
entry is added to the array.

The issue I have is if the user adds and then deletes the same row, I end up with two entries:

["add:123456789:0:0", "del:123456789:0:0"]


How can I get the
del
to overwrite the add (and/or) edit entry matching on the ID ?

I've tried:

rows = rows.map(function(value) {
if( value.indexOf(id) > -1 ) {
return false;
}

return value;
});


but that just replaces the entry with 'false' it doesn't delete it.

Any idea how I can do this ?

Thanks

Joe Joe
Answer

jQuery.map will work as you expect. undefined or null return values will not be mapped.

rows = $.map(rows, function(value) {
    if( value.indexOf(id) > -1 ) {
        return undefined;
    }

    return value;
    });

jQuery map callback function can return:

  • the translated value, which will be mapped to the resulting array
  • null or undefined, to remove the item
  • an array of values, which will be flattened into the full array