grep

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.