jQuery in Action
172
CHAPTER 6
jQuery utility functions
When the callback is specified as a string, jQuery automatically generates a call-
back function using the passed string as the value of the
back function using the passed string as the value of the
return
statement and
passing two parameters:
a
for the current value and
i
for the current index. So
the generated function for this example is equivalent to
function(a,i){return a>100;}
Even though the
$.grep()
function doesn't directly use regular expressions
(despite its name), JavaScript regular expressions can be powerful tools for us to use
in our callback functions to determine whether to include or exclude values from the
resultant array. Consider a situation in which we have an array of values and wish to
identify any values that don't match the pattern for United States Postal Codes (also
known as
in our callback functions to determine whether to include or exclude values from the
resultant array. Consider a situation in which we have an array of values and wish to
identify any values that don't match the pattern for United States Postal Codes (also
known as
ZIP
Codes).
US
Postal Codes consist of five decimal digits optionally followed by a
dash and four more decimal digits. A regular expression for such a pattern would
be
be
/^\d{5}(-\d{4})?$/
, so we could filter a source array for non-conformant
entries with the following:
var badZips = $.grep(
originalArray,
function(value) {
return value.match(/^\d{5}(-\d{4})?$/) != null;
},
true);
Notable in this example is the use of the
String
class's
match()
method to
determine whether a value matches the pattern or not and the specification of the
invert
parameter to
$.grep()
as
true
to exclude any values that match the pattern.
Collecting subsets of data from arrays isn't the only operation we might
perform upon them. Let's look at another array-targeted function that jQuery
provides.
provides.
6.3.4 Translating arrays
Data might not always be in the format that we need it to be. Another common
operation that's frequently performed in data-centric web applications is the
translation of a set of values to another set. Although it's a simple matter to write a
operation that's frequently performed in data-centric web applications is the
translation of a set of values to another set. Although it's a simple matter to write a
for
loop to create one array from another, jQuery makes it even easier with the
$.map
utility function.