Quick Tip: Fully Understanding $.grep
videos

Quick Tip: Fully Understanding $.grep()

Share

The jQuery method $.grep() is one of those methods that isn’t used as often as it should be. This is mostly because, until you understand exactly what it does, it can be a bit confusing. Hopefully, this video quick tip will explain when and why you would use it.

At its core, $.grep is a simple little method that will filter through an array and sift out any items that don’t pass a particular control. For example, if we have an array of the numbers 1-10, and want to filter out any values that are below 5, we can do:

var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');

nums = $.grep(nums, function(num, index) {
  // num = the current value for the item in the array
  // index = the index of the item in the array
  return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

View live demo on JSBin.

XEROX CODE

Or let’s say that you have an array of numbers and strings, and you want to sift out all of the strings, leaving just an array of numbers. One way that we can accomplish this task is with $.grep.

var arr = '1,2,3,4,five,six,seven,8,9,ten'.split(',');

arr = $.grep(arr, function(item, index) {
  // simply find if the current item, when passed to the isNaN,
  // returns true or false. If false, get rid of it!
  return !isNaN(item);
});

console.log(arr); // 1,2,3,4,8,9

View live demo on JSBin.

For further training, be sure to refer to the jQuery API.

Related Posts

Add Comment

Discussion 32 Comments

  1. josheat says:

    How would this differ from doing the same thing in $.each?

  2. Alvin Crespo says:

    Thanks for your time in explaining this to us.

    I personally didn’t know this existed in the JQuery library.

  3. Aqib Mushtaq says:

    i like these type of quick tips, awesome stuff.

  4. Erik says:

    That’s really helpful. Wish there was an equally awesome function in PHP for this!

    Thanks for sharing as usual!

  5. George says:

    Never used it before. Very usefull, thanks very much.

  6. David Runion says:

    $.each() is similar to $.grep in that it iterates over an array, but $.each is made to take action based on the contents of an array, not modify the array. You would have to explicitly create a new array, and array.push() it in your each function, and then re-assign the values back to the original array. If you tried to use array.splice() on your array inside of a $.each function, you would change the array’s length and that would mess up the $.each function.

    var nums = ’1,2,3,4,5,6,7,8,9,10′.split(‘,’);
    $.each(nums, function(index, num) {
    // if confused uncomment this line
    // console.log(index);
    if(num <= 5) {
    nums.splice(index, 1);
    }
    return true;
    });
    console.log(nums); // returns 2,4,6,7,8,9,10

    Jeffrey, thanks for the quick tip, keep them coming!

  7. hubeRsen says:

    great, never used that, but it seems to be really helpful in some cases.

  8. Bretticus says:

    Great Tip!

    Coming from a *nix background, I am at a loss as to why the JQuery author(s) chose to use the word ‘grep’ for this call. I mean grep is derived from “global / regular expression / print” afterall. I guess ‘filter’ was already being used. :)

    • Joshua says:

      I’m with you…

      I never new $.grep() even existed (i really need to scrape through the full api to see what i’ve missed) … but when i saw this article i was kinda thinking it was a simple way to return all elements who’s text contents match the passed arg… was confused at first when i played the video…

      Seems an unfortunate name to chose for that function….

  9. Michal Kozak says:

    Great tip.

    Actually, up until now I was using not-so-good workaround, so that’s really helpful.

  10. Teun Beijers says:

    Nice tutorial, you forgot to close the final tag btw

  11. David Moreen says:

    I never knew about this function, where have I been? In fact I was looking for something similar to this just the other day. I’m going to try to use this as an alternative to what I have.

  12. Example 1 filters out values less than 6, not 5.

  13. Neeraj Singh says:

    For the sake of completeness I would suggest to also have a look at jQuery.map function.

    http://api.jquery.com/jQuery.map/

  14. I have never heard of this function, something to look into.

  15. kevin m says:

    I think the main reason this function has been overlooked is just due to the poor choice in naming. GREP is a cornerstone command in Linux for searching for and in files with regular expressions.

    As a Linux user myself, I would have to make an alias or create another function with another name wrapping this just to keep my head straight.

  16. Gregor says:

    Really intersting Tip. Just wanted to point out that you forgot the closing LI tag at the end :-) Not that I would care. Thanks for the screencast

  17. Zoran says:

    http://www.jqueryfordesigners.com, Remi has good explanation about this, it’s the best site for learning jquery functionalities.

  18. Tim says:

    I just noticed this video has been filed under php for some reason :S

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.