I'm looking to extract a subsection of a javascript array of objects based on a certain condition, e.g:
object.property == 2
I know that I could look开发者_Python百科 through and build a new array from the ones that match, but I was wondering whether there was a shorthand for this.
You can use grep().
var arr = [ 1, 2, 3 ];
var subset = $.grep(arr,function(n,i){ return n >= 2 });
// subset = [2, 3]
Use http://api.jquery.com/filter/
e.g.
$(yourCollection).filter(function(){
return (this.property == 2);
});
EDIT: jsFiddle with both approaches benchmarked: http://jsfiddle.net/StuperUser/6AfQj/
精彩评论