UnderscoreJS:比较两个数组

时间:2017-01-11 09:42:49

标签: angularjs arrays compare underscore.js

我目前有两个数组,我想与其中一个进行比较:

阵列一:

var allCategories =
[
 { utilization:"license", id:"450", type: "MainCategory" },
 { utilization:"rating", id:"451", type: "SubCategory" },
 { utilization:"medical", id:"452", type: "MainCategory" },
 { utilization:"other", id:"453", type: "MainCategory" }
];

阵列二:

var allKinds = 
[
 { name:"name1", id:"450", type: "FAA" },
 { name:"name2", id:"451", type: "FAA" },
 { name:"name3", id:"451", type: "FAA" },
 { name:"name4", id:"451", type: "FAA" },
 { name:"name5", id:"451", type: "SPA" },
 { name:"name6", id:"451", type: "SPA" },
 { name:"name7", id:"452", type: "FBC" },
 { name:"name8", id:"453", type: "SPA" }
];

我要做的是比较检索“数组2”中的项目与利用率:“license”,“medical”& “其他”。

目前我已经从“Array One”中提取了ID:

var categories = _.filter(allCategories, function(obj) {
  return obj.utilization === 'license' || obj.utilization === 'medical' || obj.utilization === 'other';
});
var category_ids = _.pluck(categories, 'id');

第二部分,我似乎无法弄清楚: 如何将“Array one”[450, 452, 453]的结果与“Array Two”中的项目进行比较,以检索具有id的项目。

这是一个jsfiddle: https://jsfiddle.net/7n9pjrc9/

1 个答案:

答案 0 :(得分:2)

一个简单的解决方案是通过检查category_ids是否包含对象id来过滤您的列表:

var r1 = _.filter(allKinds, function(o) {
    return _.contains(category_ids, o.id);
});
console.log(r1);

或者如果您愿意,可以根据所选ID的哈希值进行过滤

var hashed = {};
_.each(categories, function(o) {
    hashed[o.id] = true;
});
var r2 = _.filter(allKinds, function(o) {
    return hashed[o.id];
});
console.log(r2);

和演示

var allCategories =
[
 { utilization:"license", id:"450", type: "MainCategory" },
 { utilization:"rating", id:"451", type: "SubCategory" },
 { utilization:"medical", id:"452", type: "MainCategory" },
 { utilization:"other", id:"453", type: "MainCategory" }
];

var allKinds = 
[
 { name:"name1", id:"450", type: "FAA" },
 { name:"name2", id:"451", type: "FAA" },
 { name:"name3", id:"451", type: "FAA" },
 { name:"name4", id:"451", type: "FAA" },
 { name:"name5", id:"451", type: "SPA" },
 { name:"name6", id:"451", type: "SPA" },
 { name:"name7", id:"452", type: "FBC" },
 { name:"name8", id:"453", type: "SPA" }
];


var categories = _.filter(allCategories, function(obj) {
  return obj.utilization === 'license' || obj.utilization === 'medical' || obj.utilization === 'other';
});
var category_ids = _.pluck(categories, 'id');

var r1 = _.filter(allKinds, function(o) {
	return _.contains(category_ids, o.id);
});
console.log(r1);

var hashed = {};
_.each(categories, function(o) {
	hashed[o.id] = true;
});
var r2 = _.filter(allKinds, function(o) {
	return hashed[o.id];
});
console.log(r2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>