我正在使用 lodash 在javascript中进行数组交集,下面是我正在尝试的代码,我得到的是
["universal", "ola", "uber", "bangalore"],
但是,我期待的是 [ “通用”]
这里,带有n个项目的 orgArr 多维数组,我的意思是, orgArr 可以有5个或6个或10个项目......例如
[["garden","canons","philips","universal"],["universal","ola","uber","bangalore"], ["ola","uber","bangalore"]];
请注意
var orgArr = [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]];
var resfinaArray = [];
for (var i = 0; i < orgArr.length; i++){
var currItem = orgArr[i];
for (var j = 0; j< orgArr.length; j++){
resfinaArray.push(_.intersection(currItem, orgArr[j]));
}
}
console.log(resfinaArray, 'resfinaArray');
请帮忙吗?
答案 0 :(得分:0)
您可以使用forEach()
循环和可选的thisArg
参数执行此操作。
var orgArr = [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]];
var resfinaArray = [];
orgArr.forEach(function(a) {
var that = this;
a.forEach(function(e) {
(!that[e]) ? that[e] = true : resfinaArray.push(e);
})
}, {});
console.log(resfinaArray);
&#13;
答案 1 :(得分:0)
使用ES6,您可以使用Set
和Array#reduce
。
var array = [["garden", "canons", "philips", "universal"], ["universal", "ola", "uber", "bangalore"], ["abc", "def", "universal"]],
result = [...array.reduce((r, a, i) =>
a.reduce((s, b) =>
(!i || r.has(b)) && s.add(b) || s, new Set), new Set)];
console.log(result);
&#13;
答案 2 :(得分:0)
我会按照以下方式完成这项工作;
var intersectArrays = a => a.reduce((p,c) => p.filter(e => c.includes(e))),
arr = [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"], ["ola","uber","bangalore", "universal"]],
brr = intersectArrays(arr);
console.log(brr);
&#13;
答案 3 :(得分:0)
你不需要循环:
var intersection = _.intersection(["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]);
如果您的数据已包含在数组中,则可以使用apply
:
var intersection = _.intersection.apply(null, [["garden","canons","philips","universal"],["universal","ola","uber","bangalore"]]);