Created
April 20, 2011 16:38
-
-
Save themasch/931857 to your computer and use it in GitHub Desktop.
grep over your js arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var grep = function(pattern, invert) { | |
invert = invert || false | |
var ret = []; | |
if(this.filter) { | |
ret = this.filter(function(element) { | |
var b = element.match(pattern); | |
return b && !invert || invert && !b; | |
}); | |
} else { | |
for(var n in this) { | |
var element = this[n]; | |
if(element.match && typeof element.match == 'function') { | |
var b = element.match(pattern); | |
if(b && !invert || invert && !b) { | |
ret.push(element); | |
} | |
} | |
} | |
} | |
return ret; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var myarray = [..some data..]; | |
// make grep a member of myarray | |
myarray.grep = grep; | |
// normal grep | |
var filterd = myarray.grep(/regexp/); | |
// invert match (-v option by grep) | |
var invert = myarray.grep(/regexp/, true); | |
// you can use grep.apply if u don't want to mess around in your objects | |
var filtered = grep.apply(myarray, [/regexp/, true]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment