我不知道如何找到这组数组的交集:
[
[
{"name":"product1","light":"1"},
{"name":"product2","light":"2"},
{"name":"product5","light":"5"},
{"name":"product4","light":"4"}
],
[
{"name":"product2","light":"2"},
{"name":"product3","light":"3"},
{"name":"product4","light":"4"}
],[...more arrays with objects]
]
这只是样本数据,我实际的设置发生了很大变化,但结构有所变化。我希望返回的相交看起来像这样(相交对象的单个数组):
[
{"name":"product2","light":"2"},
{"name":"product4","light":"4"},
]
我与LoDashjs和Underscorejs一起尝试过:
_.intersectionObjects = _.intersect = function(array) {
var slice = Array.prototype.slice; // added this line as a utility
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
//return _.indexOf(other, item) >= 0;
return _.any(other, function(element) { return _.isEqual(element, item); });
});
});
};
我需要这个,因为我正在尝试使用 knockout js创建标签系统。我有一个分类标签按钮的布局,这些标签按钮在单击时写入“过滤器”可观察数组,剩下的唯一事情就是找到此可观察数组中包含的已过滤产品的交集。
请帮帮我,我已经连续两天试图解决这个问题,但是缺乏JavaScript知识来解决。提前致谢!
最佳答案
尝试添加它们的应用方法:
var myArr = [
[
{"name":"product1","light":"1"},
{"name":"product2","light":"2"},
{"name":"product5","light":"5"},
{"name":"product4","light":"4"}
],
[
{"name":"product2","light":"2"},
{"name":"product3","light":"3"},
{"name":"product4","light":"4"}
]
]
_.intersectionObjects = _.intersect = function(array) {
var slice = Array.prototype.slice;
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.any(other, function(element) {
return _.isEqual(element, item);
});
});
});
};
var myIntersection = _.intersectionObjects.apply(_, myArr);
for (var i = 0; i < myIntersection.length; i++) {
console.log(myIntersection[i]);
}
// Sample Output:
// Object {name: "product2", light: "2"}
// Object {name: "product4", light: "4"}