Tuesday, February 16, 2010

Fully Understanding $.grep()

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

live demo

No comments:

Post a Comment