开发者

Subsection of an Array in JS/JQuery

开发者 https://www.devze.com 2023-03-25 15:37 出处:网络
I\'m looking to extract a subsection of a javascript array of objects based on a certain condition, e.g:

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消