我不知道如何找到这组数组的交集:
我需要这个是因为我正在尝试使用knockoutjs创建一个标签系统。我有一个分类的标签按钮布局,点击后会写入到一个"filter"可观察数组中,现在唯一剩下的就是找到包含在此可观察数组中的过滤产品的交集。
请帮帮我,我已经连续两天在尝试解决这个问题,但缺乏javascript知识来解决它。提前谢谢!
[
[
{"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); });
});
});
};
我需要这个是因为我正在尝试使用knockoutjs创建一个标签系统。我有一个分类的标签按钮布局,点击后会写入到一个"filter"可观察数组中,现在唯一剩下的就是找到包含在此可观察数组中的过滤产品的交集。
请帮帮我,我已经连续两天在尝试解决这个问题,但缺乏javascript知识来解决它。提前谢谢!