Quick Tip: Fully Understanding $.grep()

Quick Tip: Fully Understanding $.grep()

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.



Leave a Reply

Your email address will not be published. Required fields are marked *