I really enjoyed Josh Clanton’s article Filtering Arrays with Array.filter on using the JavaScript filter method(). As he points out,
Because the
filtermethod is part of the ECMAScript 5 specification, it isn’t available in older browsers like IE8.
Josh then lists a couple of options to bring this functionality into older browsers (i.e. IE < 9) using a shim or JavaScript library. He does not list a solution for the jQuery library. After a little research I realized the jQuery method grep provides this same functionality.
While I’m not a huge fan of the method name grep for this functionality, I’m pleased it is included in jQuery (and I understand the method filter was already being used).
// subsetArray is populated by elements of
// array where the callback function returns true
var subsetArray = jQuery.grep(
array,
function(elementOfArray, indexInArray)
[, invert ]
);
Example
var origArray = [
'apple',
'banana',
'boat',
'cat',
'cow'
];
var bArrary = jQuery.grep(
origArray,
function(el) {
// return true when first
// character is 'b'
return 'b'=== el.charAt(0)
}
);
// bArray =
// ["banana", "boat"]
photo credit: Pandiyan via photopin cc

Leave a Reply