Grep N’ Reassign Technique for Removing elements from Array of objects


Hello folks, missed me? This is a quick post for JavaScript/jQuery rookies and intermediates. Its been a couple of years that I’m mucking around with the JavaScript library called jQuery. Moving my focus suddenly from desktop applications on C++ or even C# made me confused on what this client side scripting language has become; a magic wand or just a party stunt thingy. Because as a C++ developer, there are lot of things that you may feel a euphoria upon seeing it working like a charm with JS while the same were nightmares in those well mannered programming languages.

I just want to share yet another party stunt (or a spell) which I found when I was in a serious thought of how to remove an object from an array by matching some attributes with out using any loops. I cannot give a guarantee on its performance benefits, but take a look at it. I want to call it Grep N’ Re-assign (I didn’t invent it, so giving name is a bit melodramatic I know).

If I have an array items and I want to remove a group of objects, say the ones with quantity field is ‘1’. So I would suggest the following way.

items = $.grep( items, function( e ) { return e.quantity != 1 });

That’s it! Instead of searching for the element by matching it manually using loops, we just filtered it using the grep function in jQuery library and re-assigned it to the same variable.

About these ads

2 comments

  1. I’m a big fan of grep and have used it a lot. However, it can be a performance issue. It’s just a wrapper to a for loop with a callback function test the return statement. One of the main issues I have with it is there is no way to stop the loop. It will read every record. So if you only want to remove a certain number of items, or just get one, ect… You’re better off using a loop. Here is some sample testing I’ve done http://jsperf.com/in-array-speed . I’m planning to dig a little deeper in a blog post.

    1. While I agree with the fact that there is no way to end the loop using grep, If I were to do a linear search to find “elements” that matches a particular criteria, I still don’t know when to stop as the element that satisfies the condition can appear as the last element also. But in case if you want to remove only a single element, yes. manual looping is better as you can break from it when you find the first match.

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