我正在玩数组试图了解更多,因为我最近很喜欢与他们合作.
我得到这种情况,我想搜索一个数组,并将其元素值与包含某些所选过滤器值的另一个数组进行比较.
我得到这种情况,我想搜索一个数组,并将其元素值与包含某些所选过滤器值的另一个数组进行比较.
例如,如果我选择3个过滤器,我以后要在新数组中写入匹配 – 只有匹配所有3个过滤器的匹配.
为了更容易理解,我在http://jsfiddle.net/easwee/x8U4v/36/设置了一个例子
代码是:
- var workItems = [
- { "id": 2616,"category": ".category-copy .category-beauty .category-fashion"},//this is a match
- { "id": 1505,"category": ".category-beauty"},// NOT
- { "id": 1500,"category": ".category-beauty .category-fashion"},// NOT
- { "id": 692,"category": ".category-stills .category-retouching"},// NOT
- { "id": 593,"category": ".category-beauty .category-capture .category-fashion .category-product .category-stills .category-stills-retouching "},// NOT
- { "id": 636,"category": ".category-beauty .category-copy .category-fashion"},//this is a match
- { "id": 547,"category": ".category-fashion .category-lifestyle .category-stills .category-stills-retouching "},// NOT
- { "id": 588,"category": ".category-capture .category-recent-work .category-copy .category-beauty .category-fashion"} //this is a match
- ];
- var filtersArray = [".category-beauty",".category-fashion",".category-copy"];
- var i;
- for (i = 0; i < filtersArray.length; ++i) {
- var searchString = filtersArray[i];
- console.log('Searching for: ' + searchString);
- var filtered = $(workItems).filter(function(){
- return this.category.indexOf(searchString);
- });
- }
- console.log('Filtered results: ' + JSON.stringify(filtered,null,4));
我也试过
- filtered = $.grep(workItems,function(element,index){
- return element.category.indexOf(filtersArray[i]);
- },true);
但它只匹配第一个过滤器,只有当它在workItems.category的开头
解决方法
您可以使用Array对象的.filter()方法:
- var filtered = workItems.filter(function(element) {
- // Create an array using `.split()` method
- var cats = element.category.split(' ');
- // Filter the returned array based on specified filters
- // If the length of the returned filtered array is equal to
- // length of the filters array the element should be returned
- return cats.filter(function(cat) {
- return filtersArray.indexOf(cat) > -1;
- }).length === filtersArray.length;
- });
一些像IE8这样的旧浏览器不支持Array对象的.filter()方法,如果使用jQuery可以使用jQuery对象的.filter()方法.
jQuery版本:
- var filtered = $(workItems).filter(function(i,element) {
- var cats = element.category.split(' ');
- return $(cats).filter(function(_,cat) {
- return $.inArray(cat,filtersArray) > -1;
- }).length === filtersArray.length;
- });