Multi
Multi
Vector Series - Why You Should Use $.Grep()
Topic Started: Thursday, 24. November 2011, 11:44 (263 Views)
Andrew
Member Avatar
ぼくたちがすべてはばか。
Why You Should Use $.Grep()
Difficulty: Easy
Time: 5 Minutes




Grep is a handy jQuery function that I don't really seem to see a lot. Due to $.grep()'s lack of usage I decided to make a tutorial about it. $.grep() basically iterates through every element in an array and returns the array with any elements that did or did not match the specifications removed.

Code: JavaScript: $.grep() Syntax
 
$.grep(yourArray, function(arrayElement, arrayIndex){
yourTest
}, invertOrNot)

yourArray - The array to iterate through.
arrayElement - The current element in the array.
arrayIndex - The current index in the array.
yourTest - Whatever you want to test the current element against. Must return a boolean.
invertOrNot - If this is true then an array containing every element that did not pass the specified test is returned instead of one containing every element that did pass the test.

Tip: The argument for whether to invert or not is optional.

Here's a real world example. Say you had an array filled with test scores and you only wanted the ones that were above 80. Well $.grep() is perfect for this situation.
Code: JavaScript
 
var scores = [57, 82, 48, 97, 92, 48, 86, 83, 95, 81, 89];

scores = $.grep(scores, function(score, n){
return score > 80;
}, false);

for(score in scores){
document.write(scores[score] + '<br />');
}

/*
Outputs:
82
97
92
86
83
95
81
89
*/


Have a question? Ask away.
Posted Image

Professional web design/development services.http://wildandrewlee.com/
Off
Profile
Quote
Top
 
Maddy
Member Avatar
BAMMMMM!
Outline Documentations
G E N E R A L

Documentation accepted in to the General database
Posted Image
This is a work in progress ^^

"You still talk about it? You still care about it."


Tumblr - WeHeartIt - My Things - Twitter

The List
Life
<3
Off
Profile
Quote
Top
 
1 user reading this topic (1 Guest and 0 Anonymous)
« Previous Topic · Coding & Development · Next Topic »

Welcome Guest [Log In] [Register]
Outline Live
Loading..
Loading..