Skip to content

July 14, 2012

1

Using jQuery.each() on a mutating list

by Joe Kuan

Suppose we have a scenario that an array variable (let say ‘master’) contains a list of objects. Each of these objects internally has a reference back to the variable array, so that it’s remove function can remove itself from the owner array.

If we use jQuery.each() to call the remove function on that list, such as:

$.each(master, function(idx, item) {
    item.remove();
});

then it will result with error because we will end up calling the remove function on an object that is already removed. The bottom line is that we should be careful using jQuery.each to traverse on a list and call the function that can mutate the list. However, there are two ways we can still use $.each to get around it:

  1. Make the .each function to loop in a reverse index manner, i.e. removing the items backwards. The only way I can think of is to have a range() function, reverse the range and call the reverse index list with $.each which is too much hazzle.
  2. Create a shallow copy from the master list and call it with $.each.

The second approach is much simpler:

var shallowCopy = $.extend({}, master);
$.each(shallowCopy, function(idx, item) {
    item.remove();
});

 

Read more from Javascript, jQuery, Programming, Web
1 Comment Post a comment
  1. MBR
    Aug 1 2013

    Another way that worked better for me is to just go through the array and set the array items you want to delete to null/undefined, then as a separate step use filter() to create a new array that has the holes removed.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: