Hostinicon
GET HOSTING FROM $3.95/MO PLUS A FREE YEAR ON TUTS+ (RRP $180). HURRY OFFER LIMITED. Check it out
Advertisement

Quick Tip: Fully Understanding $.grep()

by
Gift

Get a free year on Tuts+ this month when you purchase a Siteground hosting plan from $3.95/mo

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:

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.

View live demo on JSBin.

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

Advertisement