Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Quick Tip: Dissecting jQuery - Grep

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

In this latest episode of "Dissecting jQuery," we'll peal back the cover of $.grep, and learn exactly what's happening behind the scenes.

jQuery Source for grep

// jQuery source for the grep method 
grep: function( elems, callback, inv ) {
		var ret = [];

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			if ( !inv !== !callback( elems[ i ], i ) ) {
				ret.push( elems[ i ] );
			}
		}

		return ret;
	}

Hopefully, you now have a better understanding of what's happening behind the scenes. Just remember: any time that you need to remove items from an array, $.grep will do the trick quite nicely!

Advertisement