Quick Tip: Fully Understanding $.grep
videos

Quick Tip: Fully Understanding $.grep()

Tutorial Details
  • Difficulty: Intermediate
  • Completion Time: 15 Minutes

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.

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.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://eatstudio.com josheat

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

    • http://www.indev.nl Matthijn Dijkstra

      With each you would have to keep track of an array with correct values, and not insert the incorrect values yourself, this method does that for you.

  • Alvin Crespo

    Thanks for your time in explaining this to us.

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

    • http://decipherdigital.com Jon

      Likewise. Cheers.

  • http://www.aqibmushtaq.co.uk Aqib Mushtaq

    i like these type of quick tips, awesome stuff.

  • http://www.virtualerik.com Erik

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

    Thanks for sharing as usual!

  • George

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

  • David Runion

    $.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!

    • David Runion

      changing console.log(index); to console.log(‘index: ‘ + index + ‘ num: ‘ + num); would be even more educational

    • http://eatstudio.com josheat

      Yeah, I see what you mean.
      Cheers

    • http://neeraj.name Neeraj Singh

      take a look at jQuery.map . You don’t need to create an array yourself.

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

  • http://hubersen.ch hubeRsen

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

  • Bretticus

    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

      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….

  • http://twitter.com/michalkozak Michal Kozak

    Great tip.

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

  • http://beijers.eu Teun Beijers

    Nice tutorial, you forgot to close the final tag btw

  • http://spotdex.com/ David Moreen

    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.

  • http://blog.jeremymartin.name Jeremy Martin

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

    • http://blog.jeremymartin.name Jeremy Martin

      Hmm… the comment filter removed my [nitpicking] tags. Meant to say that in a less deuchey tone. :p

  • http://neeraj.name Neeraj Singh

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

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

  • http://www.jordanwalker.net Jordan Walker

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

  • http://localhost kevin m

    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.

  • http://www.vandertuin.nl Jeroen van der Tuin

    Very handy, thanks.

  • http://htmlexpress.de Gregor

    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

  • Zoran

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

  • http://tutorialblog.info/ tutorial blog

    thank for tut

  • Tim

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

  • http://jeffersonluis.com Jefferson Luís

    Hey Jeffrey, this post be in wrong category.